I have gone through the column sorting in jQuery datatable plugin and the various ways of controlling it.. I have a query is it possible to control sorting in such a way that clicking on upper arrow icon will do sorting in ascending order & down arrow icon will do sorting in descending order??
1 Answer
There is two way of doing that, depending on datatables version.
EDIT for Datatables version 1.9 or less
You need to use fnHeaderCallback. With this callback you can edit every th element in table header.
I have create a working example for you.
LIVE : http://live.datatables.net/oduzov
CODE : http://live.datatables.net/oduzov/edit#javascript,html
Here is code behind that (open 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 newer
callback have a new name, it's just headerCallback. Everything else is the same, so use new callback insted of legacy api.