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");
    }
} 
1
  • use if($(check).prop('checked')){ instead of if(check.prop('checked')){ Commented May 5, 2015 at 2:09

3 Answers 3

2

Here is another way can do,

var i = 0;
$(".checked").each(function(){
    if (this.checked){
        console.log("Checkbox number: " + i + " is checked");
        i++;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1
$('.checked').each(function (index, element) {
    if ($(this).is(":checked")) {
        console.log("Checkbox number: " + index + " is checked");
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.