views:

98

answers:

3

Hello,

So I have the following:

var box = $(".MyCheckBox");

if (box[0].checked)
{
    // Do something
}
else
{
    // Do something else
}

Is there a better way of doing this using filters or something?

I know I can go:

$(".MyCheckBox")
    .filter(function(index) {
         return this.checked;
     })
    .each(function() {
         // do something
     });

But I need to do something in the else statement... easier way of doing this? Thanks!

+5  A: 

attr('checked') returns the checked value of the first element anyway, so no [0] malarky.

if ($(".MyCheckBox").attr('checked')) {
 // Do something
} else {
 // else
}
Matt
+5  A: 

You can use the built-in :checked selector:

$(".MyCheckBox:checked").each(function() {
  //Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
  //Do something with unchecked ones..
});

Or filter in the each similar to what you have:

$(".MyCheckBox").each(function() {
  if($(this).is(":checked")) {
    //Do something with checked ones..
  } else {
    //Do something with unchecked ones..
  }
});

Or if say you wanted to toggle a class, then use a different approach, this would give the active class to the checked ones:

$(".MyCheckBox").each(function() {
  $(this).toggleClass("active", $(this).is(":checked"));
});

Update
Based on comments if you want just raw speed:

$(".MyCheckBox").each(function() {
  if(this.checked) {
    //Do something with checked ones..
  } else {
    //Do something with unchecked ones..
  }
});
Nick Craver
I believe using the :checked selector is faster than using attr.
richleland
:checked is far, far slower than attr on the test I did (http://www.jsfiddle.net/CTu7a/)
Matt
what about just doing this.checked?
Polaris878
@Polaris878 - `this.checked` is **far** faster than either method. But you're talking about an infinitesimally small difference here unless dealing with thousands of checkboxes, so what's more readable is probably better.
Nick Craver
I'll be dealing with up to a couple hundred checkboxes so it might matter :)
Polaris878
@Polaris878 - In that case, `$(".MyCheckbox").filter(function() { return this.checked; })` is about as fast as you'll get in selecting the checked ones, or use it in the each/if, either way. In my answer swap ` if($(this).is(":checked")) {` in the second code block for `if(this.checked) {`, I'll update with this example.
Nick Craver
+2  A: 

I'd go with Nick's updated answer above, but would like to suggest that you complete your selector. i.e.,

$('input.myCheckBox').each(function(){
    // tralalala...
}

... just for the fact that it makes your initial jQuery selection a bit faster. I mean, since we're debating about speed and all. ^_^

Richard Neil Ilagan