jQuery实现CheckBox全选与全不选

方式一

① 点击全选按钮实现全选与全不选
 var len = $("input[name='box']").length;  //复选框个数
        $("#allBox").click(function () {
            if($("#allBox").is(':checked')){
                $("input[name='box']").prop("checked","true");
            }else {
                var checked = $("input[name='box']:checked").length;  //复选框被选中的个数
                if (len==checked){
                    $("input[name='box']").removeAttr("checked");
                }
            }
        });

      
② 如果有一个未选中则取消全选按钮的选中状态/全都选择设置全选按钮为选中状态
var len = $("input[name='box']").length;  //复选框个数
  $("input[name='box']").click(function () {
            //复选框被选中的个数
            var checked = $("input[name='box']:checked").length;
            if (len==checked){
                $("#allBox").prop("checked","true");
            }else {
                $("#allBox").removeAttr("checked");
            }
        });

代码中allBox 代表全选按钮的id属性,box代表复选框的name属性

方式二

① 点击全选按钮实现全选与全不选
 $("#allSelBox").click(function () {   //全选框按钮点击事件
            var flg = this.checked;

            $("#userData :checkbox").each(function () {
                this.checked = flg;
            });
        });
② 如果有一个未选中则取消全选按钮的选中状态/全都选择设置全选按钮为选中状态
 $(document).on("click",".check_item",function(){ //复选框点击事件
            console.log('dsgsdfhg')
            //判断当前选择中的元素是否等于总复选框个数
            var flag = $(".check_item:checked").length==$(".check_item").length;
            $("#allSelBox").prop("checked",flag);
        });

代码中allSelBox 代表全选按钮的id属性,check_item代表复选框的class属性

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。