Jquery Datatable Callbacks

|
| By Webner

Jquery data table callbacks are used when you want to perform some action on a certain event in the data table. For eg. when you want to modify a particular row or cell every time the table is redrawn.

List of Datatable Callbacks

createdRow

When

element is created then this callback method is invoked. For example, you can write code in this callback method to attach specific css classes or JS events to the row that has just been created.

Syntax: createdRow( row, data, dataIndex )

Parameters:
row: reference to the

element which has been currently created in data table.

data: reference to the row’s data i.e data.id, data.first_name etc.

dataIndex: reference to the row index

For example:

Add a class “selected” to the row when “is_visible” column = 1

$('#reviews').dataTable({
"createdRow": function(row, data, dataIndex) {
if (data.is_visible == 1) {
$(row).addClass('selected');
}
}
});

drawCallback
It gets called every time the table is drawn or redrawn (like when data is sorted or filtered):

Syntax: drawCallback(setting)

Parameters:
setting: It refers to data table setting object.

Example:

Data table row grouping through drawcallback()

Row grouping is used when we have same values in a column and we want to create a subheading inside table with that common value and represent records having that characteristic under that heading as shown in the following screenshots:

Here in this screenshot, we want Location column to be visible as a header above the records. Here is what we want:

For this, we have to hide this column and using drawCallback method we can create groups of records. This works like group by clause in sql. Here is the code:

"columnDefs": [{
"visible": false,
"targets": 2
}, ],
"drawCallback": function(settings) {
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var emptyLast = null;
api.column(2, {
page: 'current'
}).data().each(function(egroup, i) {
if (emptyLast !== egroup) {
$(rows).eq(i).before(
'< td > ’+egroup + '

');

emptyLast = egroup;
}
});

In above example, we are performing row grouping on column “2”. In grouped row we are displaying “location” of users. To use row grouping and drawcallback event first we have to hide the grouping column “2” in “columnDefs”. Then in “drawCallback”, we get all the records using [“api.rows( {page:’current’} ).nodes();”] .Then we are just displaying the records.

Leave a Reply

Your email address will not be published. Required fields are marked *