Iterating Through All Rows Only Works on First Page
Iterating Through All Rows Only Works on First Page
I've made a fiddle here - http://jsfiddle.net/q1hk828g/
HTML
<a id="click_all" href="#">Click All</a>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Office</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>London</td>
<td><a href="#" class="link">Link</a></td>
<!-- etc -->
</tr>
</tbody>
</table>
JS
$(document).ready( function () {
var table = $('#example').DataTable();
$(document).on('click', '.link', function() {
$(this).html('CLICKED').removeClass('link');
return false;
});
$(document).on('click', '#click_all', function() {
var table = $('#example').dataTable();
var total_rows = table.fnGetData().length;
var filtered_rows = table.$('tr', {"filter":"applied"});
if (total_rows == filtered_rows.length) {
// click all rows
$('a.link', table.fnGetNodes()).click();
} else {
// only click filtered rows
console.log(filtered_rows);
for (var i = 0; i < filtered_rows.length; i++) {
$(filtered_rows[i]).find('a.link').click();
};
}
return false;
});
});
Basically, just trying to click the link for all rows if there is no filter and click the link for filtered rows if a filter is provided.
My own code is a bit more complicated than the fiddle (starts with an empty table and populated via ajax) and I thought that might be the issue but the issue is still reproducible when the data is present at the point of initialisation so if anyone can point me in the right direction as to what I'm doing wrong then I would greatly appreciate it.
This question has an accepted answers - jump to answer
Answers
Its because you are using a delegated event for the
clicked
part:The
click
occurs, but keep in mind that the way the jQuery delegated event works is that it is thedocument
that gets the actual DOM click, then jQuery looks up the child elements to see if any clicks should apply to them, Since the other rows aren't in the DOM (DataTables removes them while they are not needed) they aren't applicable.The only way around it is to use a static event handler for the
clicked
part. You could usecreatedRow
for example - updated fiddle: http://jsfiddle.net/q1hk828g/1/Btw - I've updated your click all handler to use the new chaining API in 1.10. If I understood it correctly, everything can just be done in one line now.
Allan
Hi Allan,
Thank you very much for your help, that makes sense now and the
createRow
function in the initialisation is pretty neat and will make my code a lot tidier aswell.Martin