DataTables – Default sorting by the table column header class name

DataTables is a jQuery Javascript library plug-in to convert static html tables (including dynamically generated) into dynamically viewable and sortable tables. The advantage to using this plug-in is that the end user is given control over viewing and sorting the information presented in a table.

There is one feature which I wanted to implement but had a difficult time finding the exact solution. I wanted to set the default sorting for one specific column. The function, aaSorting, handles this but requires the use of an integer indicating the location of the column header. The downside to using fixed integers is that if the column headers change at some future point, the sorting could break then requiring the fixed integer to be updated. Why can’t this be dynamic and rely on a class name for the column header, instead of a fixed integer?

The author of DataTables addresses this question and feature in a post, that also includes a work-around to accomplish setting the default sorting by using the table column header (th) class value. The author also posts a live example.

In the end, the workaround code is:

    "aaSorting": [[ $('#example thead th.default_sort').index('#example thead th'), 'asc' ]]

Leave a Reply

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

*