jQuery Implementation Simple Full Checkbox

  • 2021-08-21 19:30:15
  • OfStack

In this paper, we share the specific code of jQuery to realize simple full selection box for your reference. The specific contents are as follows

1. Requirements:

(1) When all check boxes are checked, all other check boxes are selected, and when all check boxes are unchecked, all other check boxes are unchecked
(2) When the check box is unchecked, the all check box should also be unchecked

2. HTML section


<table id="table">
  <thead><tr><th colspan="6"> Student information form </th></tr></thead>
  <tbody>
  <tr>
   <th>
   <input type="checkbox"id="checkedAll" value=" All selection " /> All selection 
   </th>
   <th> Student number </th>
   <th> Name </th>
   <th> Gender </th>
   <th> Age </th>
   <th> Credit </th>
  </tr>
  <tr>
   <td>
   <input type="checkbox" name="items"/>
   </td>
   <td>1001</td>
   <td> Millet </td>
   <td> Male </td>
   <td>23</td>
   <td>100</td>
  </tr>
  <tr>
   <td>
   <input type="checkbox" name="items"/>
   </td>
   <td>1002</td>
   <td> Xiaodong </td>
   <td> Male </td>
   <td>23</td>
   <td>50</td>
  </tr>
  <tr>
   <td>
   <input type="checkbox" name="items"/>
   </td>
   <td>1002</td>
   <td> Xiaodong </td>
   <td> Male </td>
   <td>23</td>
   <td>50</td>
  </tr>
  </tbody>
</table>

3. css section


<style type="text/css">
  *{
  margin: 0;
  padding: 0;
  }
  table,tr,td,th{
  border: 1px solid black;
  }
  #table{
  border-collapse: collapse;
  border-spacing: none;
  width: 50%;
  margin: 0 auto;
  text-align: center;
  }
  tr{
  height: 40px;
  }
</style>

4. jQuery section


<script src="js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
 <script type="text/javascript">
  $(function () {
  //  Interlaced color change effect 
  $('#table tbody>tr:even').css("background","#cccccc");
  //  Objects that define variables that receive all check boxes and other check boxes 
  var $checkedAll = $("#checkedAll");
  var $items = $(":checkbox[name=items]");
  //  All box click event 
  $checkedAll.click(function () {
   if (this.checked) { // $(this).prop("checked")
        $items.prop('checked',true);
      } else {
        $items.prop('checked',false);
      }
  })
  //  Check all check boxes when all check boxes are selected 
  $items.click(function () {
   //  When the number of unselected check boxes is 0 When, it is the time of all selection 
   if ($items.not(":checked").length===0) {
        $checkedAll.prop('checked',true);
      } else {
        $checkedAll.prop('checked',false);
      }
  })
  
  })
</script>

Related articles: