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>

猜你喜欢

转载自blog.csdn.net/weixin_45965358/article/details/114263663