I have inputs nested inside of anchors nested inside of list items. I'd like to use jquery to iterate through the list items, and if an item was selected display the values in a text field. I'm close, I'm down to the input control, but the "if (checked)" statement is not working.
Can somebody please tell me what I'm doing wrong? :(
function ddDistrictChanged() {
var txt = "nothing selected";
var $inp = $('#ddDistrict').find('input');
$inp.each(function (index) {
$('#txtHere').text($(this).children('li'));
if ($(this).checked) {
txt = txt + ', ' + $(this).text();
}
$('#txtHere2').text(txt);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ddDistrict" class="dropdown-menu">
<li><input name="selCol" type="checkbox" value="1"> District 1 (Porter)</li>
<li><input name="selCol" type="checkbox" value="2"> District 2 (Jones Jr.)</li>
<li><input name="selCol" type="checkbox" value="3"> District 3 (Horne)</li>
<li><input name="selCol" type="checkbox" value="4"> District 4 (Haddaway)</li>
<li><input name="selCol" type="checkbox" value="5"> District 5 (Duncan)</li>
<li><input name="selCol" type="checkbox" value="6"> District 6 (Willner)</li>
<li><input name="selCol" type="checkbox" value="7"> District 7 (Brady)</li>
<li><button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button></li>
</ul>
<div id="txtHere"></div>
<div id="txtHere2"></div>
Would make it cleaner if you wrapped the text in an element like <span>
<li><a ><input/><span> District 1 (Porter)</span></a></li>
Next can use :checked pseudo selector to select only checked inputs
function ddDistrictChanged() {
var txt = "nothing selected";
var $items = $('#ddDistrict').find('li has(input:checked)');
if ($items.length) {
txt = $items.map(function() {
return $(this).find('span').text()
}).get().join(', ');
}
$('#txtHere2').text(txt);
}
Working JSFiddle DEMO
To start with, lets refactor your HTML to make it a bit easier to interact with when using JavaScript/jQuery. I have opted to use labels with your inputs instead of <a> tags.
<ul class="ddDistrict dropdown-menu">
<li>
<input type="checkbox" id="cbox1" value="1" checked>
<label for="cbox1" class="small underlineText_No">District 1 (Porter)
</label>
</li>
<li>
<input type="checkbox" id="cbox2" value="2">
<label for="cbox2" class="small underlineText_No">District 2 (Jones Jr)
</label>
</li>
<li>
<input type="checkbox" id="cbox3" value="3">
<label for="cbox3" class="small underlineText_No">District 3 (Horne)
</label>
</li>
<li>
<input type="checkbox" id="cbox4" value="4">
<label for="cbox4" class="small underlineText_No">District 4 (Haddaway)
</label>
</li>
<li>
<input type="checkbox" id="cbox5" value="5">
<label for="cbox5" class="small underlineText_No">District 5 (Duncan)
</label>
</li>
<li>
<input type="checkbox" id="cbox6" value="6">
<label for="cbox6" class="small underlineText_No">District 6 (Willner)
</label>
</li>
<li>
<input type="checkbox" id="cbox7" value="7">
<label for="cbox7" class="small underlineText_No">District 7 (Brady)
</label>
</li>
<li>
<button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button>
</li>
</ul>
<div class="txtHere"></div>
I then created some basic JavaScript/jQuery to check if any checkboxes have been checked on load and update the DOM according to what has been checked, and when they are checked.
var $inputs = $('.ddDistrict input');
var $outputWrapper = $('.txtHere');
// Check for boxes that have already been checked and
// append their labels to the DOM.
$inputs.each(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
}
});
// This event handler will watch for any changes to the
// checkboxes and will append the value of their labels
// to the DOM on change.
$inputs.change(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
} else {
$('.' + currentID).remove();
}
});
It's all relatively simple stuff and the code can be refactored to make it more DRY, but this should definitely put you in the right direction. Let me know if you have any questions.
Related
I have textarea field and 3 groups of checkboxes. User can individually select any checkbox and checkbox value will be added to textarea field. But how to include "Select all" functionality to select all checkboxes in group? I created "Select all" function, but after selection values are not added to textarea field.
// Add checkbox value to text field
$checks = $("ul li :checkbox");
$checks.on("change", function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(",");
$("#results").val( "checked:" + string);
});
// Select all checkboxes in the group
jQuery(function($){
$('#allg1').click(function () { $('.group1 li input').not(this).prop('checked', this.checked);});
$('#allg2').click(function () { $('.group2 li input').not(this).prop('checked', this.checked);});
$('#allg3').click(function () { $('.group3 li input').not(this).prop('checked', this.checked);});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="results" rows="2" cols="60"> </textarea>
<ul class="group1">
<input type="checkbox" id="allg1" name="allg1"><label for="allg1">Select all from group G1</label>
<li><input type="checkbox" value="G101"></li>
<li><input type="checkbox" value="G102"></li>
<li><input type="checkbox" value="G103"></li>
</ul>
<ul class="group2">
<input type="checkbox" id="allg2" name="allg2"><label for="allg2">Select all from group G2</label>
<li><input type="checkbox" value="G201"></li>
<li><input type="checkbox" value="G202"></li>
<li><input type="checkbox" value="G203"></li>
</ul>
<ul class="group3">
<input type="checkbox" id="allg3" name="allg3"><label for="allg3">Select all from group G3</label>
<li><input type="checkbox" value="G301"></li>
<li><input type="checkbox" value="G302"></li>
<li><input type="checkbox" value="G303"></li>
</ul>
To achieve this you can trigger() the change event manually on the checkboxes when the 'Select all' is toggled. Your normal event handler will then run which updates the text in the textbox.
Also note that you can DRY up the JS controlling the 'Select all' boxes by using common class attributes on them.
jQuery($ => {
// Add checkbox value to text field
let $checks = $("ul li :checkbox").on("change", function() {
let string = $checks.filter(":checked").map((i, el) => el.value).get().join(",");
$("#results").val(string && "checked:" + string);
});
// Select all checkboxes in the group
$('.all').click(e => {
$(e.target).closest('.group').find('li input').not(e.target).prop('checked', e.target.checked).trigger('change');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="results" rows="2" cols="60"> </textarea>
<ul class="group">
<label><input type="checkbox" class="all" name="allg1">Select all from group G1</label>
<li><input type="checkbox" value="G101"></li>
<li><input type="checkbox" value="G102"></li>
<li><input type="checkbox" value="G103"></li>
</ul>
<ul class="group">
<label><input type="checkbox" class="all" name="allg2">Select all from group G2</label>
<li><input type="checkbox" value="G201"></li>
<li><input type="checkbox" value="G202"></li>
<li><input type="checkbox" value="G203"></li>
</ul>
<ul class="group">
<label><input type="checkbox" class="all" name="allg3">Select all from group G3</label>
<li><input type="checkbox" value="G301"></li>
<li><input type="checkbox" value="G302"></li>
<li><input type="checkbox" value="G303"></li>
</ul>
I have multiple divs of 3 checkboxes – each div has a show/hide button (jQuery slideUp) that hides the 'ul.task-list' to display the H2 heading.
<div class="row" id="row-0">
<button class="toggle">Toggle</button>
<h2>Row 0</h2>
<ul class="task-list">
<li><input type="checkbox" id="task-0-0" class="task" value="0" /></li>
<li><input type="checkbox" id="task-0-1" class="task" value="1" /></li>
<li><input type="checkbox" id="task-0-2" class="task" value="2" /></li>
</ul>
</div>
<div class="row" id="row-1">
<button class="toggle">Toggle</button>
<h2>Row 1</h2>
<ul class="task-list">
<li><input type="checkbox" id="task-1-0" class="task" value="0" /></li>
<li><input type="checkbox" id="task-1-1" class="task" value="1" /></li>
<li><input type="checkbox" id="task-1-2" class="task" value="2" /></li>
</ul>
</div>
I call a 'checkTotal' function, and if everything in the row is checked, add the class of "complete" and slideUp the UL.
let sections = $('.row').map(function() { return this.id }).get(); // gets id of row
const tasksTotal = 3; // the total checkboxes in each row
function checkTotal() {
sections.forEach(function(i) { // loops section IDs
let total = $('#'+i+' input:checked').length; // checked in row
total == tasksTotal ? ($('#'+i).addClass('complete'), $('#'+i+' .task-list').slideUp()) : ($('#'+i).removeClass('complete')); // add class & hide row
});
}
checkTotal();
The issue is, if I click to show row 0 (after complete) and then check anything in row 1 – it will automatically slide row 0 up again – as complete remains true (all items are checked).
I just can't figure out how to separate these, so they act independently and without looping through again.
You can passed this under your checkTotal() function which will be used to check only the checkbox which is check by user.Then we can use this to get closest ul and loop through only that part where checkbox is located and then to we need to find checkbox length which are checked we can get that using elem.find("input:checked").length.
Demo Code :
jQuery(function() {
jQuery('.toggle').on('click', function() {
jQuery(this).parent().siblings('.task-list').slideToggle();
});
const tasksTotal = 3; // the total checkboxes in each row
function checkTotal(el) {
//find closest ul
var elem = jQuery(el).closest(".task-list");
//loop through it
elem.each(function() {
//get total count of checked input
let total = elem.find("input:checked").length;
console.log(total)
//apply the same to particular ul
total == tasksTotal ? (elem.addClass('complete'), elem.slideUp()) : (elem.removeClass('complete'));
});
}
$('.task').change(function() {
checkTotal(this);//passed only the checkbox clicked
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="row-0">
<div class="options">
<h2>Row 0</h2>
<button class="toggle">Toggle</button>
</div>
<ul class="task-list" data="abd">
<li><input type="checkbox" id="task-0-0" class="task" value="0" /> <label for="task-0-0"> Item 0</label></li>
<li><input type="checkbox" id="task-0-1" class="task" value="1" /> <label for="task-0-1"> Item 1</label></li>
<li><input type="checkbox" id="task-0-2" class="task" value="2" /> <label for="task-0-2"> Item 2</label></li>
</ul>
</div>
<div class="row" id="row-1">
<div class="options">
<h2>Row 1</h2>
<button class="toggle">Toggle</button>
</div>
<ul class="task-list">
<li><input type="checkbox" id="task-1-0" class="task" value="0" /> <label for="task-1-0"> Item 0</label></li>
<li><input type="checkbox" id="task-1-1" class="task" value="1" /> <label for="task-1-1"> Item 1</label></li>
<li><input type="checkbox" id="task-1-2" class="task" value="2" /> <label for="task-1-2"> Item 2</label></li>
</ul>
</div>
I have checkboxes and radio buttons on my page.
I have some scenario.
When the user selects the first checkbox then the first radio will select and if you unchecked the checkbox then the radio button will unchecked.
If the user directly selects the radio button then the nearest checkbox will select.
The above scenarios are almost working, I am getting the issue on the second checkbox.
I select the first checkbox then the first radio button is selected. If I select the second check then the radio button is selecting but the first radio is unchecked.
$("input[type='radio']").click(function() {
$(this).closest('.reviewers-details').find('.selectRV').prop('checked', true);
});
$("input[type='checkbox']").click(function() {
var checkbox = $(this).closest('.reviewers-details').find('.selectRV').prop('checked');
if (checkbox == true) {
// $(this).closest('.reviewers-details').find('input[type=radio]').prop('checked', true);
$(this).closest('.reviewers-details').find('input[type=radio]:first').prop('checked', true);
} else if ($(this).prop("checked") == false) {
$(this).closest('.reviewers-details').find('input[type=radio]').prop('checked', false);
}
});
<div class="reviewers-details d-table sectionHeading">
<div class="d-table-cell">
<input type="checkbox" name="reviewerid[1]" class="revieweruser selectRV" value="1">test
<ul>
<li>
<input type="radio" name="reviewer_timeslot[1]" class="revieweruser" value="1">
<label>abc</label>:
</li>
<li>
<input type="radio" name="reviewer_timeslot[1]" class="revieweruser" value="3">
<label>xyz</label>:
</li>
</ul>
</div>
</div>
<div class="reviewers-details d-table sectionHeading">
<div class="d-table-cell">
<input type="checkbox" name="reviewerid[1]" class="revieweruser selectRV" value="1">demo
<ul>
<li>
<input type="radio" name="reviewer_timeslot[1]" class="revieweruser" value="1">
<label>abc</label>:
</li>
<li>
<input type="radio" name="reviewer_timeslot[1]" class="revieweruser" value="3">
<label>xyz</label>:
</li>
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
All radio buttons with the same value for their name attribute will be part of the same radio group: if one becomes selected, the others automatically become unselected.
Below, I simply renamed the radio buttons in your second group to isolate them (and their linked checkbox) from the first group.
(You may want to rename the checkbox as well, unless you have a reason for it to share a name with the first checkbox.)
$("input[type='radio']").click(function() {
$(this)
.closest('.reviewers-details')
.find('.selectRV')
.prop('checked', true);
});
$("input[type='checkbox']").click(function() {
var checkbox = $(this)
.closest('.reviewers-details')
.find('.selectRV')
.prop('checked');
if (checkbox == true) {
$(this)
.closest('.reviewers-details')
.find('input[type=radio]:first')
.prop('checked', true);
}
else if ($(this).prop("checked") == false) {
$(this)
.closest('.reviewers-details')
.find('input[type=radio]')
.prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reviewers-details d-table sectionHeading">
<div class="d-table-cell">
<input type="checkbox"
name="reviewerid[1]"
class="revieweruser selectRV"
value="1"
/>test
<ul>
<li>
<input type="radio"
name="reviewer_timeslot[1]"
class="revieweruser"
value="1"
/>
<label>abc</label>:
</li>
<li>
<input type="radio"
name="reviewer_timeslot[1]"
class="revieweruser"
value="3"
/>
<label>xyz</label>:
</li>
</ul>
</div>
</div>
<div class="reviewers-details d-table sectionHeading">
<div class="d-table-cell">
<input type="checkbox"
name="reviewerid[1]"
class="revieweruser selectRV"
value="1"
/>demo
<ul>
<li>
<input type="radio"
name="reviewer_timeslot[2]"
class="revieweruser"
value="1"
/>
<label>abc</label>:
</li>
<li>
<input type="radio"
name="reviewer_timeslot[2]"
class="revieweruser"
value="3"
/>
<label>xyz</label>:
</li>
</ul>
</div>
</div>
My javascript code like this :
$(function(){
$('input[type="radio"]').click(function(){
var txt = $(this).parent().text();
var $radio = $(this);
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
$('#result-select').text('');
}
else{
$radio.data('waschecked', true);
$('#result-select').text(txt);
}
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
Demo and full code like this : https://jsfiddle.net/oscar11/m7by6zcw/21/
I want to :
If I select chelsea, madrid and juve the result like this :
Chelsea - Madrid - Juve
If I select chelsea and madrid the result like this :
Chelsea - Madrid
So if I check radio button, it display the text. If I uncheck radio button, it not display the text
How can I do it?
Update :
The radio button can be unchecked
For example :
If I select chelsea, madrid and juve the result like this :
Chelsea - Madrid - Juve
Then I uncheck madrid, the result like this :
Chelsea - Juve
Updated fiddle: https://jsfiddle.net/m7by6zcw/37/
Basically like Justinas's answer but with the checking/unchecking available.
The only part I really changed was how the text was being outputted, shown below:
let output = [];
$('input[type="radio"]:checked').each( function() {
var txt = $(this).parent().text();
output.push(txt);
});
$('#result-select').text(output.join(' - '));
You need to reset the data of everything else when something checks:
$(`input[name=${name}]:not(:checked)`).data('waschecked', false);
You have to gather all values from :checked radio buttons, later use .join to convert array to string and place to results field
$(function(){
$('input[type="radio"]').click(function(){
var result = $('#result-select');
var results = [];
$('input[type="radio"]:checked').each(function () {
results.push($(this).closest('label').text());
});
result.text(results.join(' - '));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>England</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Chelsea
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Mu
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Arsenal
</label>
</div>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>Spain</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Madrid
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Barcelona
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Atletico
</label>
</div>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>Italy</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Juve
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Milan
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Inter
</label>
</div>
</li>
</ul>
</div>
<span id="result-select">Result</span>
You need to first get the text value of the result : var str = $('#result-select').text();, then when you check a radio button, you just append the value to the result text str += txt; $('#result-select').text(str);.
And if you uncheck a radio button, you just replace it's value with an empty string str = str.replace(txt,'');.
$(function(){
$('input[type="radio"]').click(function(){
var txt = $(this).parent().text();
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
var str = $('#result-select').text();
str = str.replace(txt,'');
$('#result-select').text(str);
}
else{
$radio.data('waschecked', true);
var str = $('#result-select').text();
str += txt;
$('#result-select').text(str);
}
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
I have given code
<ul id="payment-method-fields">
<li id="paypal">
<label>
<input checked="checked" id="order_payments_attributes__payment_method_id_5" name="order[payments_attributes][][payment_method_id]" type="radio" value="5">
Test Paypal
</label>
</li>
<li id="adyen">
<label>
<input id="order_payments_attributes__payment_method_id_4" name="order[payments_attributes][][payment_method_id]" type="radio" value="4">
Ali Pay
</label>
</li>
<li id="adyen_encrypted">
<label>
<input id="order_payments_attributes__payment_method_id_16" name="order[payments_attributes][][payment_method_id]" type="radio" value="16">
credit card
</label>
</li>
<li id="cod" >
<label>
<input id="cash-on-delivery" name="cod" type="radio" value="">
Cash on Delivery
</label>
</li>
</ul>
my requirement is when click on other li i.e on Cash on Delivery then paypal gets unchecked. Please guide me how I will write this jquery.
My proposal is:
$('#payment-method-fields :input[type="radio"]').on('change', function(e) {
if (this.id == 'cash-on-delivery') {
$('#payment-method-fields').find('input[type="radio"]:not(#' + this.id + ')').prop('checked', false);
}
});
You can do this:
$('#cash-on-delivery').on('change', function(){
$('input[name="order[payments_attributes][][payment_method_id]"]')
.prop('checked', !this.checked);
});
Simply give them the same name for all input tags
Example:
<input type="radio" name="group_name" />
This ensures only one is selected at any time.
You can give all inputs a same class for example
class="radio_button"
And then you can add code
$(document).ready(function(){
$('.radio_button').on('click',function(){
$('.radio_button').removeAttr('checked');
$(this).prop('checked','checked');
})
}
The last input has a different name <input id="cash-on-delivery" name="cod" type="radio" value=""> than the others so when you check it the others won't automatically uncheck. Give it the same name and it will work fine.
Here is an Example of it working.
Code:
<ul id="payment-method-fields">
<li id="paypal">
<label>
<input checked="checked" id="order_payments_attributes__payment_method_id_5" name="order[payments_attributes][][payment_method_id]" type="radio" value="5">
Test Paypal
</label>
</li>
<li id="adyen">
<label>
<input id="order_payments_attributes__payment_method_id_4" name="order[payments_attributes][][payment_method_id]" type="radio" value="4">
Ali Pay
</label>
</li>
<li id="adyen_encrypted">
<label>
<input id="order_payments_attributes__payment_method_id_16" name="order[payments_attributes][][payment_method_id]" type="radio" value="16">
credit card
</label>
</li>
<li id="cod" >
<label>
<input id="cash-on-delivery" name="order[payments_attributes][][payment_method_id]" type="radio" value="">
Cash on Delivery
</label>
</li>
</ul>
Removing the property 'checked' from the input-elements with the jQuery removeProp function. For your example create two functions and call them in the onClick trigger of your input-elements:
function uncheckTop3() {
$('#order_payments_attributes__payment_method_id_5').removeProp('checked');
$('#order_payments_attributes__payment_method_id_4').removeProp('checked');
$('#order_payments_attributes__payment_method_id_16').removeProp('checked');
}
function uncheckCashOnDelivery() {
$('#cash-on-delivery').removeProp('checked');
}
Here a jfiddle-link to your example.
To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:
//$('#myCheckbox').attr('checked', true); // Checks it
//$('#myCheckbox').attr('checked', false); // Unchecks it
$('#cash-on-delivery').on('change', function(){
$('input[name="order[payments_attributes][][payment_method_id]"]').attr('checked',true);
});