复选框的全选+全不选+ajax传递复选框的value值+后台接受复选框默认值

1.html代码

<!--全选框/全不选-->
<input type="checkbox" name="all" id="all" >

<input type="checkbox" name="radio" value="1">
<input type="checkbox" name="radio" value="2">
<input type="checkbox" name="radio" value="3">
<input type="checkbox" name="radio" value="4">
<input type="checkbox" name="radio" value="5">
<input type="checkbox" name="radio" value="6">

2.全选/全不选js

 //全选效果
 $("#all").click(function () {
    //判断全选框是不是checked效果
    if (this.checked) {
        //为所有的复选框加选中效果
        $("input[name='radio']").prop("checked", true);
        //$("input[name='radio']").attr("checked", true);会出现第一次能选中,再次全选中不好使的现象,可以亲身试验,我的印象很深刻
        
     } else {
        //取消所有复选框的选中效果
        $("input[name='radio']").removeAttr("checked", false);
    }
});

 

3.ajax进行复选框默认值传值

        function del() {

            //弹出提示,是否确定删除
            if (confirm("确定要删除吗?")) {

                //将所有复选框的默认值放入id数组中
                var radio = document.getElementsByName('radio');
                var id = new Array();
                //将所有选中复选框的默认值写入到id数组中
                for (var i = 0; i < radio.length; i++) {
                    if (radio[i].checked)
                        id.push(radio[i].value);
                }
                //ajax开始运行
                $.ajax({
                    url: "{:U('Index/del')}",
                    type: "post",
                    dataType: "json",
                    data: {
                        id: id
                    }
                    ,
                    success: function (msg) {
                         //ajax成功返回数据要执行的代码
                    }
                });
            }
        }

4.控制器接收ajax传递的复选框的默认值

 public function del()
    {
        //接收ajax传过来的id值(id为数组)
        $id = I('post.id');

        //判断传过来的数组是否有值
        if (!empty($id)) {
            //循环删除传过来的所有id对应的消息
            foreach ($id as $v) {
                $condition['id'] = $v;

                //删除该id对应的数据
                $result_temp = $message->where($condition)->delete();
            }
            if ($result_temp !== false) {
                $msg = $id;
                $this->ajaxReturn($msg);
            } else {
                $msg = '删除失败';
                $this->ajaxReturn($msg);
            }

        } else {
            $msg = '请进行选择再删除';
            $this->ajaxReturn($msg);
        }
    }
原文地址:https://www.cnblogs.com/jingmin/p/6380212.html