JavaScript 控制checkbox全选与全不选

1、简单定义CheckBox:

<form name="frm">
    <p>
        <label><input type="checkbox" name="selFruit" onclick="selAll(this)"/>水果:</label>
                <input type="checkbox" name="fruit" value="apple">苹果
                <input type="checkbox" name="fruit" value="banana">香蕉
                <input type="checkbox" name="fruit" value="orange">橘子
    </p>
</form>

2、onclick触发的 selAll(obj) 方法:

<script>
    /*
     * 全选与全不选
     * obj 表示使用此函数的当前对象
     */
    function selAll(obj){
        // console.log(obj.checked) //被选择就是true,不被选择就是false
        // console.log(document.frm.selFruit.checked)  //与 console.log(obj.checked) 等价

        //取所有的名字是fruit的元素
        let fruit = document.frm.fruit
        //遍历
        for(let i=0;i<fruit.length;i++){
            //把每一个checkbox的checked属性设置成当前的checkbox的checked的值
            fruit[i].checked = obj.checked
        }
    }

</script>

3、效果图

通过一个键全不选:     

通过一个键全选:

猜你喜欢

转载自blog.csdn.net/LiLi_code/article/details/86497542