Reputation: 6786
for (var chkbox in jQuery("#dialog-message input[type='checkbox']")) {
alert(chkbox.val() + " " + chkbox.is("checked"));
}
is not working; I get errors saying that val
and is
are undefined. I'd like to iterate over the check boxes inside the dialog-message
element so I can see which ones are checked and execute some other code for the ones that are, but these errors are happening instead.
Upvotes: 0
Views: 60
Reputation: 2786
JQuery has .each()
https://api.jquery.com/jQuery.each/
$('div').each(function(idx){ console.log(idx, this) })
this
being the current element. An advantage of using $.each here is arguably cleaner, more readable code and you also get the benefit of chaining.
However it is worth noting (although probably not relevant for your example) that a for loop will most likely perform (much)better when iterating over large collections of elements. For example you could write it like this;
let test = $('input');
for(let i = 0; i < test.length; i++){
console.log(test[i].checked)
}
Further, for...in will work but 1) chkbox
will be the index of the checkbox in the collection and 2) unlike my first for...
example where i will always be an integer index, for...in
this will loop over all properties of the returned JQuery object. You can use hasOwnProperty(i)
to filter out inherited properties like this;
test = $('input');
for(let i in test){
if(!test.hasOwnProperty(i)) {
continue ;
}
console.log(test[i].checked)
}
Upvotes: 0
Reputation: 21672
for...in
does not behave as you're expecting.
In your case, chkbox
is not the checkbox element; it is an integer representing the index of the item in the collection. Integers have neither a .value
nor a .checked
property, hence the undefined
error.
Instead, use jQuery's .each()
:
$("#dialog-message input[type=checkbox]").each(function() {
console.log(`${this.value} is checked: ${this.checked}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dialog-message">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" checked />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" checked />
</div>
However, if your goal is to get a collection of only the checked (or unchecked) elements, you don't need to iterate through them; you can select them using the :checked
selector (or :not(:checked)
for unchecked):
$("#dialog-message input[type=checkbox]:checked").css("zoom", "2");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dialog-message">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" checked />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" checked />
</div>
Upvotes: 1
Reputation: 1087
Use the jQuery.each() function: https://api.jquery.com/jQuery.each/
jQuery.each(jQuery("#dialog-message input[type='checkbox']"), function(index, chkbox) {
alert(chkbox.val() + " " + chkbox.is("checked"));
});
Upvotes: 0