首页 > 技术文章 > 多选框的全选与取消

dl30373 2015-07-01 09:09 原文

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        var checkbox = $('input[name=checkbox]');
        $('.selectAll').on("click",function(){
            checkbox.prop('checked', this.checked);
        });
        checkbox.on("click",function(){
            var _tmp = checkbox;
            $(".selectAll").prop('checked',_tmp.length == _tmp.filter(":checked").length);
        });
        //或者使用下述方法
        // checkbox.on("click",function(){
        //  var flag = true;
        //  checkbox.each(function(){
        //      if (!this.checked) {
        //          flag = false;
        //      };
        //  })
        //  if (flag) {
        //      $('.selectAll').prop('checked', true)
        //  }else{
        //      $('.selectAll').prop('checked', false)
        //  }
        // })
    })
    </script>
</head>
<body>
    <input type="checkbox" class="selectAll">全选/全不选<br/>
    <input type="checkbox" name="checkbox" /><br/>
    <input type="checkbox" name="checkbox" /><br/>
    <input type="checkbox" name="checkbox" /><br/>
    <input type="checkbox" name="checkbox" /><br/>
    <input type="checkbox" name="checkbox" /><br/>
    <input type="checkbox" name="checkbox" /><br/>
</body>
</html>

推荐阅读