JQuery checkbox is a handy and practical example of the simple function of selecting all the checkboxes

  • 2020-03-26 21:21:48
  • OfStack


//The main check box
<input type="checkbox" id="ck" name="ckAll">//Child check box item
<input type="checkbox" id="ck1" name="ckItm">
<input type="checkbox" id="ck2" name="ckItm">
<input type="checkbox" id="ck3" name="ckItm">


var $ckAll = $("input[name='ckAll']");
var $ckItm = $("input[name='ckItm']");
var len = $ckItm.length;
$ckAll.click(function() {
  //Gets the current selected state of $ckAll. If selected, the other subcheck boxes are selected, or otherwise canceled
    $ckItm.prop('checked',this.checked);
});
$ckItm.click(function() {
    //Bind b to judge events
    var b=$ckItm.filter(":checked").length==len;//When the number of selected subcheckboxes equals the total number, the primary checkbox is selected
    //It is judged by ternary operation
    var flag=$ckAll.prop("checked",b?true:false);
});


Related articles: