SoFunction
Updated on 2025-04-09

Based on checkbox demo(share)

This article is about check boxes, and there are two forms: 1. Select all and reverse selection are implemented by 2 buttons; 2. Select all and reverse selection are implemented by one button.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>Check boxdemo</title>
  <script src="../js/jquery-1.10." type="text/javascript"></script>
  <style>
   body{ text-align:center} 
   .con{ margin:100px auto; width:800px; height:400px; border:1px solid #F00; padding-top: 50px;} 
  </style> 
 </head>
 <body>
  <div class="con">
   <span><input type='checkbox' name='select' onclick='allSelect()'>Select all</span>
   <span><input type='checkbox' name='cancel' onclick='unAllSelect()'>Reverse selection</span>
   <span><input type='checkbox' name='fruit' />apple</span>
   <span><input type='checkbox' name='fruit' />banana</span>
   <span><input type='checkbox' name='fruit' />pear</span>
   <span><input type='checkbox' name='fruit' />peach</span>
   <span><input type='checkbox' name='fruit' />watermelon</span>
   
   <br><br><br>
   
   <span><input type='checkbox'  name='allBook' />Select all</span>
   <span><input type='checkbox' name='book' />I</span>
   <span><input type='checkbox' name='book' />Shangshu</span>
   <span><input type='checkbox' name='book' />Zhou Yi</span>
   <span><input type='checkbox' name='book' />Book of Poetry</span>
   <span><input type='checkbox' name='book' />Mencius</span>
   <span><input type='checkbox' name='book' />Mean</span>
   
<script type="text/javascript">
 //Select all function allSelect(){
  $("input[name='fruit']").prop("checked", "checked");
  $("input[name='cancel']").removeAttr("checked");
 }
 //Reverse selection function unAllSelect(){
  $("input[name='fruit']").removeAttr("checked");
  $("input[name='select']").removeAttr("checked");
 }
 //Single choice $("#allBook").click(function(){
  if(){
//   $("input[name='book']").attr("checked", true);
   $("input[name='book']").prop("checked", "checked");
   }else{
//   $("input[name='book']").attr("checked", false);
   $("input[name='book']").removeAttr("checked");
   }
 });
</script>

  </div>
 </body>
</html>

I encountered a problem in practice - check all selection is invalid. Workaround, use the prop method instead of attr.

$("input[name='book']").attr("checked", "checked"); 
$("input[name='book']").prop("checked", "checked"); 

This may be related to the jQuery version.

The above article is based on the check box demo (sharing) which is all the content I share with you. I hope it can give you a reference and I hope you can support me more.