简体   繁体   中英

Determine if all checkboxes within jQuery object are checked, return as boolean

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?

@Adam is off just a bit

if( $group1.filter(':not(:checked)').length === 0){
  //continue is OK
}

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
}

I would suggest that you give your checkboxes aa class then

 var len = $('.check_needed').length;
 var chk = $('.check_needed:checked').length;
 if (len == check){
    //carry on
 }else{
    // go home
 }

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.

You can use also

$(function(){

// add multiple select / deselect functionality
$("#selec_all_chk").click(function () {
      $('.chk_class').attr('checked', this.checked);
});

// if all checkbox are selected, check the selectall checkbox
// else uncheck
$(".chk_class").click(function(){

    if($(".chk_class").length == $(".chk_class:checked").length) {
        $("#selec_all_chk").attr("checked", "checked");
    } else {
        $("#selec_all_chk").removeAttr("checked");
    }

});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM