Custom soring function not working
Custom soring function not working
kajacx
Posts: 1Questions: 1Answers: 0
I have followed https://datatables.net/development/sorting on how to create a custom sorting function, but it doesn't work. Here is my code:
$('#dataTables-example').DataTable({
responsive: true,
columnDefs: [
{searchable: false, targets: 0},
],
"columnDefs": [
{ "sType": "string", "aTargets": [ 1 ] }
],
"language": {
"search": "Vyhledávání:",
"lengthMenu": "Zobrazit _MENU_ záznamů na stránku",
"zeroRecords": "Žádné vyhovující záznamy",
"info": "Zobrazena strana _PAGE_ z _PAGES_ (celkem _TOTAL_ pacientů)",
"infoEmpty": "Žádné dostupné záznamy",
"infoFiltered": "(celkem nalezeno z _MAX_ celkových záznamů)",
"paginate": {
"previous": "Předchozí",
"next": "Následující"
}
}
});
//TEST: use locale sorting
console.log("TEST 6");
jQuery.fn.dataTableExt.oSort['string-asc'] = function(x,y) {
console.log("TEST");
return x.toString().localeCompare(y.toString());
};
jQuery.fn.dataTableExt.oSort['string-desc'] = function(x,y) {
console.log("TEST2");
return y.toString().localeCompare(x.toString());
};
However, I only see "TEST 6" in console, and not "TEST" nor "TEST2", even if I'm spamming the sort button on all columns. What am I doing wrong? Also, what is the difference between "columnDefs" and "columnDefs"?
This discussion has been closed.
Answers
I had same problem, i have solved this by changing, type from 'string' to any other word. It is big mindfuk for me aswell !
No clue why chaing type to anything diffrent than 'string' fixed sorting functions... Really weird.
Any1 could say, why is it working that way?
"sType" is old, simply use "type". Also, as @epicatization pointed out, I would provide your own special type name to this column.
Column config
Custom sorting function
However, I have had numerous issues with '-asc' & '-desc' not firing. Alternatively, I would simply use the '-pre' notation as DataTables is pretty smart in its sorting. This allows you to format the data for appropriate sorting. Be aware that using this overrides '-asc' & '-desc'.