samedi 14 février 2015

How to set checked value of checkbox on filtered rows in a jQuery dataTable?

I am using jQuery DataTable v. 1.9.4. (A newer version is out but the version is not related to my question per se - I am forced to use some older libraries at the moment).


Setup



  1. jQuery dataTable

  2. filtered data

  3. paging enabled and filtered data spans multiple pages.


I am trying to set checked state on checkboxes in a filtered dataTable that (can) span multiple pages. I can only get my code to set the checked state on the checkboxes on the first page (maybe visible rows?) but any subsequent pages remain unchecked.


This is my code



<html>
<head>
<script src="http://ift.tt/P5n50R"></script>
<script src="http://ift.tt/1EunH61"></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" />
</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) {
var random = data + full[0];
return '<input type="checkbox" value="' + full[0] + '" id="' + random + '"/><label for="' + random + '" class="checkbox-label"/>';
};

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>


Debugging filteredRows shows that it contains all the filtered data, e.g. for keyword Spain filteredRows has 4 rows:



var filteredRows = $(dtTable).dataTable()._('tr', { "filter": "applied" });


My jQuery skills needs sharpening :-) - I suspect my problem is with the following piece of code. Any help is appreciated.



filteredRows.forEach(function (row) {
$('#mytable input[value="' + row[0] + '"]').prop('checked', checked);
});




Aucun commentaire:

Enregistrer un commentaire