user3770935 user3770935 - 4 months ago 19
jQuery Question

Datatables get drawn data

I am trying to retrieve the data from my table which is drwan to the screen.

I am able to get the table data on each redraw, however it is the full dataset rather than what is drawn to the screen.

$(document).ready(function() {
var table = $('#myTable').DataTable({
dom: 'Blfrtip',
buttons: [
{
extend: 'excel',
text: 'Download Excel'
}
]
});
$('#myTable').on('draw.dt', function (){
console.log(table.data());
});
$('#search-category').bind('input propertychange',function(){
table
.column(3)
.search(this.value)
.draw();
}),
$('#search-sub-category').bind('input propertychange', function(){
table
.column(4)
.search(this.value)
.draw();
})
} );


My aim is to get on each redraw, the table data which is actually shown to the user.

https://jsfiddle.net/qbcnsjo8/

Answer

Use rows().data() API method to retrieve data for some or all rows based on specific criteria.

To retrieve data for rows with search applied:

table.rows({ search: 'applied' }).data();

To retrieve data for rows on current page with search applied:

table.rows({ 'page': 'current', search: 'applied' }).data();

From the documentation:

The order of the data in the returned array and which rows the data is obtained from (searched rows, visible rows etc) is controlled by the selector-modifier option of the rows() selector used to get the selected rows.

See updated example for code and demonstration.