Java全栈学习---JavaScript:复选框的全选和取消

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script type = "text/javascript">
        window.onload = function(){
            var checkBox = document.getElementById("checkBox")
               checkBox.onclick = function(){
                    var check = document.getElementById("checkBox");
                    var fru = document.getElementsByName("fruits");
                    for(var i in fru){
                        fru[i].checked = check.checked;
                    }
            }
        }
    </script>
    <label for="checkBox"></label><input type = "checkbox" id = "checkBox"/>全选<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "orange"/>
    </label>orange<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "apple"/>
    </label>apple<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "pear"/>
    </label>pear<br/>
</body>
</html>

在这里插入图片描述
我们可以更加完善一下我们的程序,当我们选中下面的全部时候,自动勾选“全选”。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script type = "text/javascript">
        window.onload = function(){
            var check = document.getElementById("checkBox")
            var fru = document.getElementsByName("fruits");
               check.onclick = function() {
                   for (var i in fru) {
                       fru[i].checked = check.checked;
                   }
               }
            /**
             * 以下代码为全选则自动勾选全选中框
             */
            for(var j=0; j<fru.length; j++){
                fru[j].onclick = function(){
                    var fruitsCount = 0;
                    for(var j=0; j<fru.length; j++){
                        if(fru[j].checked === true){
                            fruitsCount++;
                        }
                    }
                        document.getElementById("checkBox").checked = (fruitsCount === fru.length);
                }
            }
            
        }
    </script>
    <label for="checkBox"></label><input type = "checkbox" id = "checkBox"/>全选<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "orange"/>
    </label>orange<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "apple"/>
    </label>apple<br/>
    <label>
        <input type = "checkbox" name = "fruits" value = "pear"/>
    </label>pear<br/>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值