views:

33

answers:

4

Hey all. I've been been trying to figure this out for a while now.

I create a jQuery object of checkboxes and store it in a variable:

$group1 = $('#checkbox1,#checkbox2,#checkbox3,#checkbox4');

The user cannot continue unless all checkboxes in that group are checked.

I've been using an if statement combined with .is(':checked') to find a boolean value:

if( $group1.is(':checked') ){
  //continue is OK
}

...but .is(':checked') will return TRUE if any checkboxes are checked within the group. Essentially, .is(':checked') performs an OR operation on the selected elements in $group1. I'm looking for an AND operation, so all selected elements must be checked to return TRUE. Is there a jQuery function that does this, or another workaround?

+1  A: 

Corrected:

You could filter to get only the elements that are not checked, and then check to see if any are any elements still in the collection, if there are not than all the elements in the group are checked:

if( $group1.filter(':not(:checked)').length === 0){
  //continue is OK
}
Adam
If all the checkboxes have to be checked, then `$group1.length == $group.filter(':checked').length` might be more appropriate
Marc B
Doesn't solve his problem...he's not looking to see if ANY are checked - he's looking to see if ALL are checked. (Although, it's an easy fix.)
JasCav
The logic here would ensure that at least one of the checkboxes is checked rather than ensuring that all of them are.
BBonifield
Oh, my mistake. I corrected the problem.
Adam
A: 

I would suggest that you give your checkboxes a a class then

 var len = $('.check_needed').length()
 var chk = $('.check_needed:checked').length()
 if (len == check){
    //carry on
 }else{
    // go home
 }
mcgrailm
adam's solution is basiclly the same EDIT: well BBonified's is
mcgrailm
+6  A: 

@Adam is off just a bit

if( $group1.filter(':not(:checked)').length === 0){
  //continue is OK
}
BBonifield
Example can be found here: http://www.jsfiddle.net/FgY32/1/
JasCav
nice and concise
mcgrailm
Much more elegant than my solution!
Daniel Sellers
This is a great solution, works perfectly. Thanks BBonifield and Adam, and everyone else!
namklabs
A: 

I think you need something like:

$(document).ready(function(){
   var checked = true;

   $('input:checkbox').each(function(){
      if(checked){
         checked = $(this).is(':checked');
      }
   });
});

This should set checked = false if any of them are unchecked.

Daniel Sellers