确定是否检查了jQuery对象中的所有复选框,返回为boolean

大家好。 我一直在努力解决这个问题。

我创建了一个复选框的jQuery对象并将其存储在一个变量中:

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

除非检查该组中的所有复选框,否则用户无法继续。

我一直在使用if语句结合.is(':checked')来查找一个布尔值:

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

…但如果在组内选中任何复选框,则.is(':checked')将返回TRUE 。 基本上, .is(':checked')对$ group1中的所选元素执行OR运算。 我正在寻找AND操作,因此必须检查所有选定的元素以返回TRUE 。 有没有一个jQuery函数可以做到这一点,或另一种解决方法?

@Adam关闭了一点

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

更正:

您可以过滤以仅获取未 检查的元素,然后检查是否仍有任何元素仍在集合中,如果组中的所有元素都没有被选中:

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

我想你需要这样的东西:

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

如果未选中任何一个,则应设置checked = false。

我建议你把你的复选框给一个class级

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

你也可以用

$(函数(){

 // 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"); } }); 

});