js and jQuery realize the functions of all selection and reverse selection

  • 2021-07-26 06:49:47
  • OfStack

js and jq realize the functions of all selection and reverse selection:

js: Idea: 1. Click the Select All button to realize, and select all the following contents, and reverse selection. 2. If one of the following items is not selected, the Select All button will not be checked, and all will be selected when all are selected. A counter is introduced here to judge whether all are selected.


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 </head>
 <body>
  All selection <input type="checkbox" name="allchoose" id="box" onclick="chk()"/>
 <div id="lower">
   Apple <input type="checkbox" name="apple" id="apple"/>
   Banana <input type="checkbox" name= "banner" id="banner" />
   Orange <input type="checkbox" name="origin" id="origin"/>
 </div>
 <script type="text/javascript">
  var box = document.getElementById("box");
  var lb = document.getElementById("lower");
  var lber = lb.getElementsByTagName("input");
 // All selection, anti-selection 
 box.onclick = function(){
  if(this.checked){
  for(var i=0;i<lber.length;i++){
   lber[i].checked = true;
  }
  }else{
  for(var i=0;i<lber.length;i++){
   lber[i].checked = false;
  }
  }
 }
 // After all the following are selected, the all selection box will be ticked 
 for(var i=0;i<lber.length;i++){
  lber[i].onclick = function(){
  // Introduced counter sum
  var sum = 0;
  for(var j=0;j<lber.length;j++){
   if(lber[j].checked){
   sum += 1;
   if(sum == lber.length){
    box.checked = true;
   } else {
    box.checked = false;
   }
   }
  }
  }
 }
 </script>
 </body>
</html>

jq, introduce jq before using jQuery:


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 </head>
 <body>
 <input type="checkbox" value=" All selection " id="ckAll"/> Fruit </br>
 <div class="box">
  <input type="checkbox" value=" Apple " id="apple"/> Apple 
  <input type="checkbox" value=" Banana " id="bann"/> Banana 
  <input type="checkbox" value=" Orange " id="origin"/> Orange 
 </div> 
 <script src="js/jquery-1.8.3.min.js"></script>
 <script type="text/javascript">
         // To all  .box input  Element addition  checked = ckAll  The current state; 
         //prop('checked',value) , No. 1 1 Gets the property by a value, the 2 Values: Set the property value. prop Only 1 Gets the element attributes when the. 
          $('#ckAll').click(function(){
               $('.box input').prop('checked',$(this).prop('checked'));
  });
  $('.box input').click(function(){
  //each  Convenient per 1 Element, let it perform the function 
  $('.box input').each(function(){
   if(!$(this).prop('checked')){
   $('#ckAll').prop('checked',false);
   // Have 1 If you are not satisfied,   Jump out of the loop and avoid performing the following 
   return false;
   }else{
   $('#ckAll').prop('checked',true);
   }
  })
  })</script>
 </body>
</html>

Related articles: