DataTables Column Search

I spend a lot of time displaying data. And I have developed a bit of a code crush on DataTables since I learned about them. Here’s an example of how the data displayed in two tables can be linked together by a select element and DataTables column search, taken from my example of xml transformed to html in the browser. Here’s how it looks when you narrow the view down to a single group (groups from 3 to 1 and users from 14 to 5)

Narrow to a Single Group

My example has two tables. The group table displays a set of groups (name, description, founder and headquarters). The sDom parameter configuration hides the standard Search box.

1
2
3
$("table.grouptable").dataTable({
sDom: 'lrtip'
});

Group Table

And the user table displays a set of users (name and group affiliations). The iDisplayLength parameter of -1 requests that the full table be displayed - too much when the full table is displayed, but nice when the table is narrowed.

1
2
3
4
5
$("table.usertable").dataTable({
sDom: 'lrtip',
aLengthMenu: [[5,10,25,50,-1],["5","10","25","50","All"]],
iDisplayLength: -1
});

User Table

I use a select2 select box to tie the two tables together. The select box is populated with the group names and configured to include place holder text and allow the selection to be cleared (click on the x and then click on the place holder text to clear the selection).

1
2
3
4
$("select.grouplist").select2({
placeholder: "narrow to single group",
allowClear: true
});

When a selection is made (“select2:select”), I search both the 1st column (0-based index) of the group table and the 2nd column of the user table for the group name. I’m using an upper case DataTables() to access the search method (and I should have used this when initializing the table as well - this will hopefully serve as a reminder). Search invocations are cumulative, so the search(“”) clears any previous search before executing a new search on the group name. And finally, the draw method requests an update of the table display.

1
2
3
4
5
$("select.grouplist").on("select2:select",function(e) {
var id = e.params.data.id;
$("table.grouptable").DataTable().column(0).search("").search(id).draw();
$("table.usertable").DataTable().column(1).search("").search(id).draw();
});

Similarly, I clear the search on unselect (“select2:unselecting”).

1
2
3
4
$("select.grouplist").on("select2:unselecting",function(e) {
$("table.grouptable").DataTable().column(0).search("").draw();
$("table.usertable").DataTable().column(1).search("").draw();
});