Sorting columns in jQuery datatables

I went through sorting columns in a jQuery datatable plugin and various ways to manage it. I have a request that you can control sorting so that clicking on the top arrow icon will sort in ascending order and the down arrow icon will sort in descending order.

+3
source share
1 answer

There are two ways to do this, depending on the version of datatables .

EDIT for Datatables version 1.9 or less

You need to use fnHeaderCallback . With this callback, you can edit every th element in the table header.

I have created a working example for you. LIVE: http://live.datatables.net/oduzov CODE: http://live.datatables.net/oduzov/edit#javascript,html

Here is the code behind this (open the snippet to see the code):

 $(document).ready(function($) { var table = $('#example').dataTable({ "fnHeaderCallback": function(nHead, aData, iStart, iEnd, aiDisplay) { // do this only once if ($(nHead).children("th").children("button").length === 0) { // button asc, but you can put img or something else insted var ascButton = $(document.createElement("button")) .text("asc"); var descButton = $(document.createElement("button")) .text("desc"); // ascButton.click(function(event) { var thElement = $(this).parent("th"); // parent TH element var columnIndex = thElement.parent().children("th").index(thElement); // index of parent TH element in header table.fnSort([ [columnIndex, 'asc'] ]); // sort call return false; }); descButton.click(function(event) { var thElement = $(this).parent("th"); var columnIndex = thElement.parent().children("th").index(thElement); table.fnSort([ [columnIndex, 'desc'] ]); return false; }); $(nHead).children("th").append(ascButton, descButton); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://legacy.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script> <table id="example" class="display" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$3,120</td> </tr> <tr> <td>Garrett Winters</td> <td>Director</td> <td>Edinburgh</td> <td>63</td> <td>2011/07/25</td> <td>$5,300</td> </tr> </tbody> </table> 

For Datatables version 1.10 and later

the callback has a new name, it's just headerCallback . Everything else is the same, so use a new callback based on the deprecated api.

+6
source

All Articles