1

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");
    }
} 
cody
  • 507
  • 7
  • 19

3 Answers3

2

Here is another way can do,

var i = 0;
$(".checked").each(function(){
    if (this.checked){
        console.log("Checkbox number: " + i + " is checked");
        i++;
    }
});
Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
1

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.

Community
  • 1
  • 1
iDev247
  • 1,761
  • 3
  • 16
  • 36
1
$('.checked').each(function (index, element) {
    if ($(this).is(":checked")) {
        console.log("Checkbox number: " + index + " is checked");
    }
});
Hoyen
  • 2,511
  • 1
  • 12
  • 13