2017-02-26 131 views
0

我使用通過使用此代碼選擇頁面中所有的複選框:選擇所有選中的複選框

$(function(){ 

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

    // if all checkbox are selected, check the selectall checkbox 
    // and viceversa 
    $(".case").click(function(){ 

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

    }); 
}); 

在這段代碼中選擇所有checkedbox。但是,如果我們選擇一些複選框,並選擇所有選擇全部。在我們再次取消選中之後,除了上一個複選框之外,其餘的都保持選中。

+2

而不是'$(「# ('checked',false);'try'$(「#selectall」)。attr(「checked」,false);' –

+0

$(「#selectall」)。 – Coder

+0

不是'attr',夥計們; 'prop'。 –

回答

0

$('.case').attr('checked', this.checked);attr部分是不正確:複選框的當前選中的狀態由checked屬性表示。 checked屬性只是the default checked stateinput,而不是其當前的檢查狀態。 (就像value屬性和value屬性之間的差異)

要設置複選框的當前狀態,使用prop

$(function() { 
 

 
    // add multiple select/deselect functionality 
 
    $("#selectall").click(function() { 
 
     $('.case').prop('checked', this.checked); 
 
    }); 
 

 
    // if all checkbox are selected, check the selectall checkbox 
 
    // and viceversa 
 
    $(".case").click(function() { 
 
     $("#selectall").prop("checked", $(".case").length == $(".case:checked").length); 
 
    }); 
 
});
<div><label><input type="checkbox" class="case"> One</label></div> 
 
<div><label><input type="checkbox" class="case"> Two</label></div> 
 
<div><label><input type="checkbox" class="case"> Three</label></div> 
 
<div><label><input type="checkbox" class="case"> Four</label></div> 
 
<div><label><input id="selectall" type="checkbox"> ALL</label></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>