【发布时间】:2015-04-15 19:23:27
【问题描述】:
我在 jQuery 数据表中设置复选框处于选中状态时遇到问题。
我的设置
- jQuery DataTable v. 1.9.4
- 过滤数据
- 启用分页和过滤的数据跨越多个页面。
我正在尝试在(可以)跨越多个页面的过滤数据表中的复选框上设置选中状态。我只能让我的代码在第一页上的复选框(可能是可见行?)上设置选中状态,但后续页面上的任何复选框都保持未选中状态。
这是我的代码 - 在这里提琴:http://jsfiddle.net/ohj8t5kL/2/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="http://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div id="myform">
<input type="checkbox" id="selectall" /><label for="selectall">Select all</label>
| Search <input type="text" value="" id="dtSearch">
<table id="mytable"></table>
</div>
<script>
var myList = function () {
var dtTable;
var init = function (){
dtTable = $('#mytable').dataTable({
"aaData": [
["1", "name1", "1@example.org", "United States"],
["2", "name2", "2@example.org", "Spain"],
["3", "name3", "3@example.org", "Spain"],
["4", "name4", "4@example.org", "United States"],
["5", "name5", "5@example.org", "Spain"],
["6", "name6", "6@example.org", "Spain"]
],
"iDisplayLength": 3,
"aoColumns": [
{ "sTitle": "", "bVisible": true, sWidth: "10%", "mRender": renderCheckBox },
{ "sTitle": "", "bVisible": true, sWidth: "25%" },
{ "sTitle": "", "bVisible": true, sWidth: "25%" },
{ "sTitle": "", "bVisible": true, sWidth: "40%" }
],
"bInfo": false,
"bLengthChange": false,
"sDom": "trp"
});
$('#dtSearch').on('keyup', dtFilter)
$('#myform').on('click', '#selectall', selectAll);
};
var dtFilter = function () {
dtTable.fnFilter($('#dtSearch').val());
};
var renderCheckBox = function (data, type, full) {
return '<input type="checkbox" value="' + full[0] + '" id="c' + full[0] + '"/>';
};
var selectAll = function () {
var checked = $('#selectall').prop('checked');
// get all filtered rows
var filteredRows = $(dtTable).dataTable()._('tr', { "filter": "applied" });
filteredRows.forEach(function (row) {
$('#mytable input[value="' + row[0] + '"]').prop('checked', checked);
});
};
return {
Init : init
};
}();
myList.Init();
</script>
</body>
</html>
在方法selectAll 中调试filteredRows 表明它正确包含过滤后的数据,例如对于关键字西班牙,filteredRows 包含 4 行:
var filteredRows = $(dtTable).dataTable()._('tr', { "filter": "applied" });
我怀疑我的问题出在以下代码上。任何帮助表示赞赏:
filteredRows.forEach(function (row) {
$('#mytable input[value="' + row[0] + '"]').prop('checked', checked);
});
【问题讨论】:
-
(我知道已经很晚了,但是)@ElliottPost 该插件与 DataTables 1.9.4 不兼容(没有它的版本)。
-
@nonzaprej 啊,对不起。我不记得我在使用插件时使用了哪个版本的 Datatables。该插件在其他方面效果很好,但显然不适用于 1.9.4。
标签: jquery checkbox datatable filtering