Si Stone Si Stone - 1 year ago 45
jQuery Question

Get all rows from DataTable including those filtered out

I am using the excellent jQuery Datatables plugin.

I have a simple table, where the first column of each row is a checkbox with class

.chk-items
.

I want users to be able to select a number of rows, and then perform an action on all those rows which have had the checkbox checked. This may include checking one or more boxes, using the SEARCH facility to filter, then checking other boxes. This of course does mean that some rows which are checked are no longer visible (i.e. they have been filtered out).

I currently have the following to handle the checked rows:

var tableData = new Array([]);
var idx = 0;
$('.chk-items').each(function() {
//Add checked items to next tab
if($(this).is(':checked')) {
//Get the selected row data into an array
var rowData = (this).closest('tr').children("td").map(function() {
return $(this).text();
}).get();
tableData[idx] = rowData;
idx = idx + 1;
}
})


However, this doesn't work when one of the checked rows is filtered out by a search.

Can anyone suggest a way to change this to also handle checked rows filtered out by the search?

Answer Source

SOLUTION

Use DataTables API method $() to perform a jQuery selection action on the full table.

var table = $('#example').DataTable();

// ... skipped ...

var tableData = [];
table.$('.chk-items').each(function() {
   // Add checked items to next tab
    if($(this).is(':checked')) {
        // Get the selected row data into an array
        var rowData = $(this).closest('tr').children("td").map(function() {
            return $(this).text();
        });

        tableData.push(rowData);
    }
});

DEMO

See this jsFiddle for code and demonstration.

LINKS

See jQuery DataTables - How to add a checkbox column for more information on using checkboxes with jQuery DataTables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download