原生js实现复选框的全选,取消全选,当子选项改变时会影响全选框的选种状态

原生js实现复选框的全选,取消全选,当子选项改变时会影响全选框的选种状态

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function chkAll() {
            var chk = document.getElementById("chk");
            // console.log(chk.checked);
            var chkAlls = document.getElementsByClassName("chk1");
            // console.log(chkAlls.length);
            for (var i = 0; i < chkAlls.length; i++) {
                chkAlls[i].checked = chk.checked;
                // console.log(chkAlls[i].checked);
            }
        }
        function chkAll1(){
            var chk = document.getElementById("chk");
            var chkAlls = document.getElementsByClassName("chk1");
            var sum=0;
            var k;
            for(var i=0;i<chkAlls.length;i++){
                if(chkAlls[i].checked==true){
                    sum++
                }else{
                    k=i;
                }
            }
            if(sum==4){
                chk.checked = true;

            }else{
                chk.checked=false;
            }

        }
    </script>
</head>
<body>
<table>
    <tr>
        <td><input type="checkbox" id="chk" onclick="chkAll()">全选</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="chk1" onclick="chkAll1()"></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="chk1" onclick="chkAll1()"></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="chk1" onclick="chkAll1()"></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="chk1" onclick="chkAll1()"></td>
    </tr>
</table>
</body>
</html>
发布了42 篇原创文章 · 获赞 12 · 访问量 6137

猜你喜欢

转载自blog.csdn.net/Alingyuzi/article/details/103879268