jQuery checkBox 全选的例子

表单处理时常常会有全选的功能,可是这个功能每每会被忽视一个细节,就是逐个选中 checkBox 直至全选时,常常会忘记修改全选 checkBox 的状态,某知名互联网公司的网盘就会出现这样的问题,问题如图:javascript

因此,须要给 checkBox 的点击事件作一下处理:点击时遍历一下除了全选的单选框以外的全部单选框,若是有未选中的,则全选不选中,若是所有都选中了,则修改全选框的状态,如下是我写的一个简单的例子:html

运行结果:java

如下就是例子的所有代码:jquery

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="content-type" content="text/html; charset=GBK"/>
    <style>
        ul,li{
            list-style:none;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        function clickAll(){
            $(".checkOne").prop("checked",$(".checkAll").prop("checked"));
        }
        
        function clickOne(){
            var allChecked = true;
            $(".checkOne").each(function(){
                if($(this).prop("checked") == false){
                    allChecked = false;
                };
            });
            if(allChecked){
                $(".checkAll").prop("checked",true);
            } else {
                $(".checkAll").prop("checked",false);
            }
        }
    </script>
</head>
<body>
<ul>
    <li><input type="checkBox" class="checkAll" onclick="clickAll()" id="all"/><label for="all">爱好(全选)</label></li>
    <br/>
    <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck1"/><label for="ck1">足球</label></li>
    <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck2"/><label for="ck2">网球</label></li>
    <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck3"/><label for="ck3">篮球</label></li>
</ul>
</body>
</html>

一块儿学习,有问题欢迎拍砖吐槽……学习

相关文章
相关标签/搜索