jQuery realizes the functions of all selection and no selection of CheckBox

  • 2021-07-10 18:20:19
  • OfStack

No more nonsense, just post the code for everyone. The specific code is as follows:


<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>jQuery Realization CheckBox Choose all, don't choose all </title> 
<script src="http://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>   
<script type="text/javascript"> 
    $(function() { 
    $(':checkbox').click(function(evt){ 
      //  Prevent bubbling  
      evt.stopPropagation(); 
    }); 
      // Judge whether to select all  
      $("#checkAll").click(function() { 
        $('input[name="subBox"]').prop("checked",this.checked);  
      }); 
      var $subBox = $("input[name='subBox']"); 
      $subBox.click(function(){ 
        //alert($subBox.length); 
        //alert($("input['subBox']:checked").length); 
        $("#checkAll").prop("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false); 
      }); 
      // Used to check whether the , Prompt value if selected  
      $("#butt").click(function (){ 
        //$('input[name="subBox"]').prop("checked",this.checked);  
        var arrChk=$("input[name='subBox']:checked"); 
        $(arrChk).each(function(){  //each()  Ergodic function  
          alert(this.value);             
        });  
        if(arrChk.length==0){ 
          alert(" Not selected ") 
        } 
      }); 
    }); 
  </script> 
</head> 
<body> 
  <div> 
    <input id="checkAll" type="checkbox" /> All selection  
    <input name="subBox" type="checkbox" value="1" /> Options 1 
    <input name="subBox" type="checkbox" value="2"/> Options 2 
    <input name="subBox" type="checkbox" value="3"/> Options 3 
    <input name="subBox" type="checkbox" value="4"/> Options 4 
    <input type="button" id="butt" value=" Check whether it is selected "/> 
  </div> 
</body> 
</html> 

jQuery Version Issue

Originally, the operation attribute was used $("XXX").attr("attrName");

While the version of jQuery uses 2.1. 1, there is a compatibility and stability problem.

jQuery API clearly states that jQuery of 1.6 + should be judged by the attributes of prop, especially checked of checkBox.

That is, the code used is as follows:


$("input[name='checkbox']").prop("checked"); 
$("input[name='checkbox']").prop("disabled", false); 
$("input[name='checkbox']").prop("checked", true);

Therefore, attr was changed to prop, and the problem was solved.

Related reading:

jQuery Operation Check Box (CheckBox) Value Assignment Implementation Code

Operation of jQuery to checkbox Check Box Select All, Do Not Select All and Reverse Select

Jquery EasyUI realizes the method of displaying checkbox on treegrid and taking the selected value


Related articles: