How do I can iterate through all checkboxes on the page with JQuery?
I.e. I have those checkboxes
above...
<div>
<input checked="checked" type="checkbox" name="option_1" id="checkbox_1" value="1" />35 MM
<input checked="checked" type="checkbox" name="option_2" id="checkbox_2" value="2" /> DIGITAL
<input type="checkbox" name="option_3" id="checkbox_3" value="3" /> 3D DIGITAL
</div>
Have I use
$('input[id^="checkbox_"]').each(function() {
});
Is it correct? Thank you!
How do I can iterate through all checkboxes on the page with JQuery?
I.e. I have those checkboxes
above...
<div>
<input checked="checked" type="checkbox" name="option_1" id="checkbox_1" value="1" />35 MM
<input checked="checked" type="checkbox" name="option_2" id="checkbox_2" value="2" /> DIGITAL
<input type="checkbox" name="option_3" id="checkbox_3" value="3" /> 3D DIGITAL
</div>
Have I use
$('input[id^="checkbox_"]').each(function() {
});
Is it correct? Thank you!
Share Improve this question asked Aug 14, 2012 at 13:47 NoWarNoWar 37.6k82 gold badges338 silver badges514 bronze badges 1- Assuming you only want inputs that have an ID beginning with "checkbox_" then yes, that code is correct. – Anthony Grist Commented Aug 14, 2012 at 13:49
5 Answers
Reset to default 8$("input[type='checkbox']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
var ischecked = $(this).is(":checked"); //check if checked
});
You can use this to iterate through the checkboxes:
$("input:checkbox").each(function() {
alert($(this).val());
});
jQuery supports a selector :checkbox
that is just for selecting checkboxes on the page so if you want all checkboxes on the page that's the simplest way to do it:
$(":checkbox").each(function(index, element) {
// put your code here
});
In the jQuery doc for :checked
, they remend that this selector might perform slightly faster:
$("input[type='checkbox']").each(function(index, element) {
// put your code here
});
$('input[type="checkbox"]').each(function() {
...
});
It seem alright but you can add further type check to ensure not other control type with mataching id es in selector.
$('input[type=checkbox][id^="checkbox_"]').each(function() {
});