jQuery realizes the selection of all buttons

 jquery is relatively simple to implement compared to js

<input type="checkbox" id="all"><br>
<input type="checkbox" name="sub"/>1<br>
<input type="checkbox" name="sub"/>2<br>
<input type="checkbox" name="sub"/>3<br>
<input type="checkbox" name="sub"/>4
<script src="js/jquery-1.12.4.js"></script>
<script>
    $("#all").on("click",function () {
        if(this.checked){
            $("input[name='sub']").attr("checked",true);
        }else {
            $("input[name='sub']").attr("checked",false);
        }
    })
</script>

However, there is a problem with selecting all and deselecting all in this way. After selecting all and deselecting all for the first time, clicking select all again for the second time will fail. At this time, use the prop() method to solve this problem. Replace the js code with the following code to realize the selection and deselection of all buttons.

$("#all").on("click",function () {
    $("input[name='sub']").prop('checked',this.checked);
});
$("input[name='sub']").on("click",function () {
    var $sub=$("input[name='sub']");
    $("#all").prop("checked" , $sub.length == $sub.filter(":checked").length ? true :false);
})

Guess you like

Origin blog.csdn.net/m0_60237095/article/details/129832286