Veuge Clavijo Veuge Clavijo - 7 months ago 7
Javascript Question

javascript array of checkboxes

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");
}
}

Answer

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.