I have to iterate an array of checkboxes asking if the checkbox is checked but I couldn't get the results. Here is my code
var checkboxes = $(".checked");
for (var i = 0; i < checkboxes.length; i++) {
var check = checkboxes[i];
if(check.prop('checked')){
console.log("Checkbox number: " + i + " is checked");
}
}
3 Answers 3
Here is another way can do,
var i = 0;
$(".checked").each(function(){
if (this.checked){
console.log("Checkbox number: " + i + " is checked");
i++;
}
});
answered May 5, 2015 at 2:11
Lumi Lu
3,3011 gold badge14 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
By doing checkboxes[i] in the loop it returns DOM elements instead of jQuery elements.
You can wrap checkboxes[i] with $() to make the DOM element a jQuery element:
var checkboxes = $(".checked");
for (var i = 0; i < checkboxes.length; i++) {
var check = $(checkboxes[i]);
if(check.is(':checked')){
console.log("Checkbox number: " + i + " is checked");
}
}
I also changed .prop('checked') to .is(':checked'). It depends which version of jQuery you're using prop might be fine (>1.6). Check out this question.
answered May 5, 2015 at 2:07
iDev247
1,9113 gold badges19 silver badges36 bronze badges
Comments
$('.checked').each(function (index, element) {
if ($(this).is(":checked")) {
console.log("Checkbox number: " + index + " is checked");
}
});
answered May 5, 2015 at 2:11
Hoyen
2,5291 gold badge15 silver badges13 bronze badges
Comments
lang-js
if($(check).prop('checked')){instead ofif(check.prop('checked')){