Reputation: 145
I have trouble getting values of all checkboxes which are selected. These checkboxes are inside list which is wrapped inside a div. Like below:
<div id="accDC">
<ul id="chkDC">
<li><a href="javascript:void(0);">
<label class="checkbox">
<input id="9" type="checkbox" value="9"> Brazil </input>
</label>
</a></li>
<li class="active"><a href="javascript:void(0);">
<label class="checkbox">
<input id="14" type="checkbox" value="14"> Germany </input>
</label>
</a></li>
</ul>
</div>
When I try to do this:
$('#chkDC input:checkbox').on('change', function () {
getAllValue()
});
getAllValue returns me string which is actually comma separated values:
function getAllValue() {
var sThisVal = '';
$('#chkDC input:checkbox').each(function () {
sThisVal = sThisVal + (this.checked ? $(this).val() : "") + ',';
});
alert(sThisVal);
}
Currently this alert is like: ,9,,,,,14,,18 which is obvious because getAllValue is called on each checkbox selection change event.
How can I call it only for < li > elements which have class = '.active' ?
Below does not seems to work, I tried:
$('#accDC > li.active > input:checkbox').on('change', function () {
alert('new selector');
getAllValue()
});
ADDITIONAL INFO: This list of checkboxes have lots of items which I am building dynamically.
Upvotes: 1
Views: 267
Reputation: 60
Your JQuery "on" function has wrong syntax in following code :
$('#accDC > li.active > input:checkbox').on('change', function () {
alert('new selector');
getAllValue()
});
Syntax should be
.on( events [, selector ] [, data ], handler )
Read on event documentation for reference.
Try the below code.
$('#chkDC > li.active').on('change','input[type=checkbox]', function () {
alert('new selector');
getAllValue()
});
Upvotes: 0
Reputation: 67217
Try,
The event binding should be like this,
$('#chkDC li.active :checkbox').on('change', getAllValue);
And the getAllValue function should be,
function getAllValue() {
var values = $('#chkDC li.active :checkbox:checked').map(function () {
return this.value;
}).get().join(); //9,12, ... return values of checked check boxes
}
Upvotes: 1
Reputation: 20636
Try the below code by binding click on li.active
; use :checked
pseudo selector,
$('#chkDC li.active input:checkbox').on('change', function () {
getAllValue()
});
function getAllValue() {
var sThisVal = $('#chkDC :checkbox:checked').map(function () {
return this.value;
}).get();
alert(sThisVal);
}
Upvotes: 1
Reputation: 62498
As #accDc has no direct child li and also li don't have checkbox direct child, you need to apply following selector:
Change it to this:
$('#accDC li.active input:checkbox').on('change', function () {
alert('new selector');
getAllValue()
});
Upvotes: 0
Reputation: 3712
The proper selector for checkboxes is:
$('input[type="checkbox"]');
And if you want the checked ones:
$('input[type="checkbox"]:checked');
Upvotes: 1