美文网首页我爱编程
jQuery实现CheckBox全选与全不选

jQuery实现CheckBox全选与全不选

作者: Specime | 来源:发表于2018-03-22 23:17 被阅读0次

方式一

① 点击全选按钮实现全选与全不选
 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属性

相关文章

网友评论

    本文标题:jQuery实现CheckBox全选与全不选

    本文链接:https://www.haomeiwen.com/subject/mwazqftx.html