Reputation: 4905
I'm trying to sort 2 columns with the DataTable plugin for jQuery (latest version). With that, It's okay onload.
$('#example').dataTable( {
"aaSorting": [ [2,'asc'], [3,'asc'] ],
});
I have little difficulties to sort 2 columns on click. For exemple, when the user click on 'album', the table is not sorting the TrackNo column. My table looks like this:
-------------------------------------
| Album | TrackNo |
-------------------------------------
| MyAlbum 2010 | 1 out of 12 |
| MyAlbum 2010 | 9 out of 12 |
| MyAlbum 2010 | 10 out of 12 |
| MyAlbum 2010 | 4 out of 12 |
| MyAlbum 2010 | 2 out of 12 |
| MyAlbum 2010 | 12 out of 12 |
-------------------------------------
Another problem is when I sort the column "Album", The TrackNo Column is sorted with this order: 1, 10, 12, 2, 4, 9.
I've noticed that it's possible to change how DataTable sorts things with:
jQuery.fn.dataTableExt.oSort['numericstring-case-asc'] = function(x,y) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['numericstring-case-desc'] = function(x,y) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
My question is: how can I sort the TrackNo column so it will display tracks in the good order without adding a zero in front of each tracks? And how do I sort 2 columns on click?
Upvotes: 1
Views: 5544
Reputation: 2653
Use the following code to create a dataTableExt oSort method that meets your requirements:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"hybrid-asc": function(x, y) {
if (!isNaN(parseInt(x)) && !isNaN(parseInt(y))) {
x = parseInt(x);
y = parseInt(y);
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},
"hybrid-desc": function(x, y) {
if (!isNaN(parseInt(x)) && !isNaN(parseInt(y))) {
x = parseInt(x);
y = parseInt(y);
}
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
});
To control one dataTable column with two columns, disable the first column's sort function and add a class to the header
HTML: <th class="sortAlbum">Album</th>
Run the following script to initialize the dataTable, set the sort method, disable the first column's sort and make the click of the the first column's header sort the second column
Js:
$(document).ready(function() {
var dataTableEx = $('#example').dataTable({
"aaSorting": [[1, 'asc']],
"aoColumns": [
{
"bSortable": false},
{
"bSortable": true,
"sType": "hybrid"}]
});
dataTableEx.fnSortListener($('.sortAlbum'), 1);
});
Upvotes: 4