I have a list checkbox's
within a div which is not a form.
<div id="priceTree">
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center"> </span></div>
</div>
This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?
I have a list checkbox's
within a div which is not a form.
<div id="priceTree">
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center"> </span></div>
</div>
This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?
Share Improve this question asked Apr 18, 2014 at 8:08 maxummaxum 2,9154 gold badges36 silver badges49 bronze badges5 Answers
Reset to default 6Here is a vanilla JavaScript solution:
var checkedCbs = document.querySelectorAll('#priceTree input[type="checkbox"]:checked');
var ids = [];
for (var i = 0; i < checkedCbs.length; i++) ids.push(checkedCbs[i].id);
//return ids;
Demo
Try this
$("#priceTree input:checked").each(function(){
console.log(this.id);
});
Demo
If you want an array of checked elements' ids, use:
var result = $('#priceTree input:checked').map(function() {
return this.id;
}).get();
THE WORKING DEMO.
$('input[type=checkbox]:checked').attr('id');
To iterate over all checkboxes use each:
$('input[type=checkbox]:checked').each(function(){
console.log($(this).attr('id'));
});
Or,
$('#priceTree :checked').each(function(){
console.log($(this).attr('id'));
});
To get ids of all checkboxes checked within #priceTree
div:
$('#priceTree input:checked').each(function(){
alert($(this).attr('id'));
})