如何在页面加载后单击复选框时选中所有复选框。
我的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>
单击按钮后会显示剩余复选框。代码是,
$list .= "<td><input id='checkBox' class='checkbox' type='checkbox' value='{$dl['id']}'></td>";
我的jquery代码是,
$('#selectall').click(function () {
if (this.checked) {
$(':checkbox').each(function () {
this.checked = true;
});
} else {
$(':checkbox').each(function () {
this.checked = false;
});
}
});
此代码无效,因为我认为复选框在页面加载后出现。我该如何解决这个问题?
答案 0 :(得分:0)
$(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"> 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>
答案 1 :(得分:0)
您可以在#selectall
点击后附加动态复选框,如下例所示。我在你的html中添加了额外的tr来追加它。您可以在代码段上看到结果。
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>