简体   繁体   English

使用jQuery加载页面后检查所有复选框

[英]Check all checkboxes after page load with jQuery

How to select all checkboxes while click on a checkbox after page load. 如何在页面加载后单击复选框时选中所有复选框。

my html code is, 我的HTML代码是,

 <table id="dealer_select_list" class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Customer Name</th>
                    <th><input id="selectall" type="checkbox">Select All</th>
                </tr>
            </thead>
            <tbody id="Dlist_cont">

            </tbody>
        </table>

Remaining checkboxes are displayed after a button click. 单击按钮后会显示剩余复选框。 And the code is, 代码是,

 $list .= "<td><input id='checkBox' class='checkbox' type='checkbox' value='{$dl['id']}'></td>";

my jquery code is, 我的jquery代码是,

  $('#selectall').click(function () {
    if (this.checked) {
        $(':checkbox').each(function () {
            this.checked = true;
        });
      } else {
        $(':checkbox').each(function () {
            this.checked = false;
        });
    }
   });

This code is not working because I think the checkboxes are appearing after page load. 此代码无效,因为我认为复选框在页面加载后出现。 How can I resolve this problem? 我该如何解决这个问题?

 $(document).ready(function(){ $('#selectall').click(function () { $(":checkbox",$("#Dlist_cont")) .prop("checked",this.checked? "checked":""); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="dealer_select_list" class="table table-bordered table-striped"> <thead> <tr> <th>Id</th> <th>Customer Name</th> <th><input id="selectall" type="checkbox">&nbsp;&nbsp;&nbsp;Select All</th> </tr> </thead> <tbody id="Dlist_cont"> <tr><td>1</td><td>C1</td><td><input type="checkbox"></td></tr> <tr><td>2</td><td>C2</td><td><input type="checkbox"></td></tr> </tbody> </table> 

You can append your dynamic checkbox after #selectall click like below example. 您可以在#selectall点击之后附加动态复选框,如下例所示。 I add extra tr to your html to append this. 我在你的html中添加了额外的tr来追加它。 You can see result on snippet. 您可以在代码段上看到结果。

  var $list = "<td><input id='checkBox' class='checkbox' type='checkbox' value='{$dl['id']}'>New one</td>"; $('#selectall').click(function () { if (this.checked) { $("#dealer_select_list #test").html('').append($list); $(':checkbox').each(function () { this.checked = true; }); } else { $(':checkbox').each(function () { this.checked = false; }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="dealer_select_list" class="table table-bordered table-striped"> <thead> <tr> <th>Id</th> <th>Customer Name</th> <th><input id="selectall" type="checkbox">Select All</th> </tr> <tr id='test'><tr> </thead> <tbody id="Dlist_cont"> </tbody> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM