javascript Realizes All Checks or Counter Checks

  • 2021-07-16 01:12:38
  • OfStack

The following is the implementation of check box all selection/reverse selection with native js. When checkbox is selected, the effect of all selection is realized and the style changes.
The most concise code, js behavior optimization version, copy and paste can be used.


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title> Checkboxes are all selected / Realization of reverse selection effect </title>
 <style>
  body,dl,dt,dd,p{margin:0;padding:0;}
  body{font-family:Tahoma;font-size:12px;}
  label,input,a{vertical-align:middle;}
  label{padding:0 10px 0 5px;}
  a{color:#09f;text-decoration:none;}
  a:hover{color:red;}
  dl{width:120px;margin:10px auto;
  border-radius:5px;background:#fafafa;}
  dt{padding-bottom:10px;
  border-bottom:1px solid #666;}
  dt label{font-weight:700;}
  p{margin-top:10px;}
 </style>
</head>
<body>
 <dl>
 <dt><input type="checkbox" id="checkAll" /><label> All selection </label><a href="javascript:;"> Reverse selection </a></dt>
 <dd>
  <p><input type="checkbox" name="item" /><label> Options ( 1 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 2 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 3 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 4 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 5 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 6 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 7 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 8 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 9 ) </label></p>
  <p><input type="checkbox" name="item" /><label> Options ( 10 ) </label></p>
 </dd> 
</dl>
<script type="text/javascript">
(function(){
 var aInput = document.getElementsByTagName("input");
 var aBack = document.getElementsByTagName("a")[0];
 var aLabel = document.getElementsByTagName("label")[0];
 var allInput = aInput[0];
  // Select all settings , When the click event occurs, if it is selected, it is all selected and the text content changes 
  allInput.onclick=function(){
   if(aInput[0].checked){
   for(var i=1;i<aInput.length;i++){
    aInput[i].checked = true;
   }
    aLabel.innerHTML = " Do not choose at all ";
   }
   else{
    for(var i=1;i<aInput.length;i++){
    aInput[i].checked = false;
    }
    aLabel.innerHTML = " All selection ";
   }

  }
  // Backcheck setting, the selected content is the reverse of the original content 
  aBack.onclick=function(){
   for(var i=1;i<aInput.length;i++){
    aInput[i].checked = !aInput[i].checked;
   }
  }
})();
</script>
</body>
</html>

Related articles: