jquery - 有没有办法在数据表中添加一个“全选”复选框来检查下表行中的所有复选框
问题描述
我的页面上有多个动态表,每一行都有一个复选框,我正在分配一个从 sql 查询中获取的值。在下面附上截图:-
有时可以有超过 5-10 张桌子。
这是我的表结构的把手代码
<div id="collapse_{{major_location_id}}" class="collapse show" aria-labelledby="heading data-parent="#accordion">
<div class="card-body">
<div class="common_table table-responsive search-input tablecolumnLimit">
<table class="table locations-table">
<thead>
<tr>
<th>
<label class="custom_checkbox">
<input class="chk_all" type="checkbox">
<span class="checkmark"></span>
</label>Location Name
</th>
<th>Address</th>
<th>City</th>
<th>Zipcode</th>
</tr>
</thead>
<tbody>
{{#each locations}}
<tr>
<td>
<label class="custom_checkbox">
{{#if (eq type 'participant')}}
<input type="checkbox" class="chk_cls"
name="participant_locations[]" value="{{location_id}}">
{{else}}
<input type="checkbox" class="chk_cls"
name="non_participant_locations[]" value="{{location_id}}">
{{/if}}
<span class="checkmark"></span>
</label>{{location_name}}</td>
<td>{{this.address1}}</td>
<td>{{this.donor_city}}</td>
<td>{{this.zip}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
</div>
这是我的数据表脚本。
$(document).ready(function () {
// var rowCount = $('#myTable tr').length;
var table = $('.locations-table').dataTable();
$(".chk_all").on('click', function () {
/* I want to check all the checkboxes that exists in the table which **this** button
belongs to. Keeping in mind the hidden checkboxes due to pagination.
});
)};
以下代码仅适用于单个表:
$("#chk_all").on('click', function () {
var cells = table.api().cells().nodes();
$(cells).find('.chk_cls').prop('checked', this.checked);
});
解决方案
在 Andrew 给出的建议中修改后对我有用。我使用 $(this) 找到离我的 Check All 复选框最近的表,然后使用变量获取所有单元格。
$(".chk_all").on('click', function () {
var myTable = $(this).closest(table);
var cells = $(myTable).dataTable().api().cells().nodes();
$(cells).find('.chk_cls').prop('checked', this.checked);
});
推荐阅读
- php - Card Connect 从响应头中获取 X-CardConnect-SessionKey
- qt - 在 Flickable 中获取缩放的 QML 项目的左上角位置
- c# - 将 DataTable 序列化为 GeoJSON 对象?
- c++ - 未定义与已删除与未声明函数
- reactjs - React 与 React-Router 在 localhost 上工作,但在 cPanel 上部署后无法获取 api 调用
- linux - Linux 上 ls -l 命令中的点是什么?
- matlab - 从 CSV 导入 Matlab 的表格,变量名以“x___”为前缀
- python - 如何解决错误“找不到 pywin32 的匹配发行版”?
- bash - 使用 awk 将计算从多个文件输出到单个多列文件
- ios - 使用 apns-expiration 处理过期的 VOIP 推送