My datatable was acting cool and all until I added a link to each integer element of a particular column. All of a sudden the sorting feature was acting weird.
Before I had something like this
23
After adding a link, I have
23
It turns out after I added the links, the default sorting function is treating everything as string. So to fix that I will need to add custom sort function to explicitly tell datatable how I want to do my sorting.
jQuery.fn.dataTableExt.oSort['intComparer-asc'] = function (a, b) {
var m = a.match(/^(d+)/);
a = m[1];
var m = b.match(/^(d+)/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 value2) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['intComparer-desc'] = function (a, b) {
var m = a.match(/^(d+)/);
a = m[1];
var m = b.match(/^(d+)/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 value2) ? -1 : 0));
};
$(document).ready(function() {
$('#my_datatable').each( function(){
oTable = $(this).dataTable({
'bPaginate': false,
'bInfo': false,
'bFilter': false,
'aoColumnDefs': [
{ 'sType': 'intComparer', 'aTargets': [ 0, 1 ] }
]
});
});
});
The key part is the line " { ‘sType’: ‘intComparer’, ‘aTargets’: [ 0, 1 ] }". As you can see, I have my first column and second column assigned to this custom new data type called intComparer. And intComparer-asc and intComparer-desc will take care of the sorting details.