tags:

views:

177

answers:

6

Hello,

I'm looping through multiple checkboxes with the same class with function each() and inside the loop I need to be able to tell whether the checkbox is checked or not. How to do that?

$('.checkbox').each(function() {
    var is_checked = 'no';
    // I need to change the value of the is_checked variable to 'yes'
    // if the checkbox is checked
    //
});
+3  A: 

Use

var is_checked = this.checked ? 'yes' : 'no';
BalusC
+1  A: 

One way is:

$('#yourcheckbox').is(':checked');
Jeremy Morgan
That's true, but it's harder to read and slower than just saying `this.checked`. You don't have to use jQuery syntax for everything you do, the DOM does still exist.
bobince
Absolutely, I was trying to keep it within the jquery code he already has, but you're right this.checked is probably faster, and more simple.
Jeremy Morgan
+2  A: 

Why not use the :checkbox:checked selector instead? That way you get the list of all the checkboxes that are checked and iterate over those.

Agent_9191
A: 

This will get all the unchecked boxes

$("input:not(:checked)")

Dve
A: 

I believe $(this).val() will give you "true" if checked and then $(this).val("true") will set the value

J.13.L
A: 
$("input:checkbox[class='.checkbox']:checked").each(function () {
 // this will only loop thru checked boxes (checked = true)
}

OR

$('.checkbox').each(function() {    
 // or return a boolean for each one
 var is_checked = $(this).is(":checked");
});
Chad