2016-01-05 96 views
2

我想让选择所有的复选框,我陷入了一些问题。如何在所有项目未选中时取消勾选“全选”复选框?

如何取消“全选”复选框,当所有项目选中?

这是我试过的代码。

<input id="select-all" type="checkbox" name="select-all-cam"> 
<span class="txt-label">Select All</span> 

<div class="list"> 
    <ul> 
     <li> 
      <input id="cam-1" type="checkbox" name="select-cam"> 
      <label for="cam-1">item1</label> 
     </li> 
     <li> 
      <input id="cam-2" type="checkbox" name="select-cam"> 
      <label for="cam-2">item2</label> 
     </li> 

    </ul> 
</div> 

$('#select-all').click(function(event) { 
    if (this.checked) { 
     $('.list input[type="checkbox"]').each(function() { 
      this.checked = true; 
     }); 
    } else { 
     $('.list input[type="checkbox"]').each(function() { 
      this.checked = false; 
     }); 
    } 
}); 

演示:https://fiddle.jshell.net/0j19t3g5/

回答

7

你可以一个change事件侦听.list添加到复选框件,确定是否选中的复选框的数量是一样的总数。

Updated Example

$('.list input[type="checkbox"]').on('change', function() { 
    var allChecked = $('.list input:checked').length === $('.list input').length; 
    $('#select-all').prop('checked', allChecked); 
}); 

的好处这种方法是,如果所有其他复选框被选中的“全选”复选框被选中,并且同样不被选中,如果他们中的一个没有被选中。

我也改变了click事件监听到change事件侦听器。您也可以缩短你的初始事件侦听器以下几点:

$('#select-all').on('change', function() { 
    $('.list input[type="checkbox"]').prop('checked', this.checked); 
}); 
0

试试这个代码

$('.list input[type="checkbox"]').on('change', function() { 
     if($('.list input:checked').length === $('.list input').length){ 
     $('#select-all').prop('checked', true);} 
     else{ 
     $('#select-all').prop('checked', false); 
     } 
    }); 
1

添加该代码了。

$(".list input[type=checkbox]").change(function(event){ 
       var checked_count = $(".list input[type=checkbox]:checked").length; 
       var max_checks = $(".list input[type=checkbox]").length;; 
       if(checked_count==max_checks){ 
       $('#select-all').prop("checked",true); 
       }else{ 
       $('#select-all').prop("checked",false); 
       } 
    }); 
0

下面的代码将取消选择所有,如果的一个未选择

$('#select-all').click(function(event) { 
    var _this = this; 
    $('.list input[type="checkbox"]').prop('checked', _this.checked); }); 
    $('.list input[type="checkbox"]').on('change', function() { 
     $('#select-all').prop("checked", this.checked); 
     var allChecked = $('input[type="checkbox"]').reduce(function(input1, input2) { 
         return input1 && input2; 
         }, true); 
     if(allChecked) { 
     $('#select-all').prop("checked", false); 
     } 
    }); 
相关问题