jquery Implementation Check Box Select All Operation Instance Code

  • 2021-07-15 03:39:05
  • OfStack

jquery Implementation Check Box All Select Operation Example Code

Recently made a demand, need to achieve the list of check box all/cancel all-select operation, because before this is not very understanding, so from the Internet to look up some information, although there are various ways to achieve, but did not find direct can be applied. After thinking about it myself, the functions are realized and sorted out as follows.

If there is any room for improvement in the implementation details, please feel free to comment.

First of all, the code of html part, here is a table, and there are 1 options in the table:

<div id="list"> 
    <tr><td> Options 1<input type="checkbox" name="group" value="1"/></tr> 
    <tr><td> Options 2<input type="checkbox" name="group" value="2"/></tr> 
    <tr><td> Options 3<input type="checkbox" name="group" value="3"/></tr> 
 All selection <input type="checkbox" id="all"/>   

Next up is jquery:

$(document).ready(function () { 
  // Choose all or not at all  
  $("#all").click(function () { 
    if (this.checked) { 
      $("#list :checkbox").attr("checked", true); 
    } else { 
      $("#list :checkbox").attr("checked", false); 
  // Set the All Check Box  
  $("#list :checkbox").click(function () { 
  function allchk() { 
    var chknum = $("#list :checkbox").size();// Total number of options  
    var chk = 0; 
    $("#list :checkbox").each(function () { 
      if ($(this).attr("checked")) { 
    if (chknum == chk) {// All selection  
      $("#all").attr("checked", true); 
    } else {// Incomplete selection  
      $("#all").attr("checked", false); 
  // Execute when displayed 1 Times  

When all check boxes are clicked, the selected state is judged, and if it is selected, the selected attributes are set for the check boxes of all options; If unchecked, the properties are unchecked for the check boxes of all options.

At the same time, add judgment for each option check box. When all option check boxes are selected, all check boxes are automatically selected; Otherwise, the All box is unchecked. This is compared by counting (the number of options and the number of selected options) and traversed by the each method.

Finally, it is performed once at the time of display, which is to ensure that if the initial state is the state where all options are selected, the all check boxes are also selected.

Reference: Simple example demonstration of checkbox in jquery

Related articles: