複選框的全選+全不選+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);
        }
    }

 

發佈了42 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章