I need to sort a column by weekdays (mon, tue, wed, thu, fri, sat, sun) and cannot seem to get this working. Note that I am using the latest 1.10 version of datatables.
This is located along with other extensions in its own file and called after jquery.dataTables.js is loaded, but before the table initialization.
/* custom sorting by weekday */
$.extend( $.fn.dataTableExt.oSort, {
"weekday-pre": function ( a ) {
return $.inArray( a, ["SUN","MON","TUE","WED","THU","FRI","SAT"] );
},
"weekday-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"weekday-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );
then in my table initialization I specify the sort for this particular column. Values can/will only be "SUN","MON","TUE","WED","THU","FRI","SAT" coming from the database.
"columns": [
..... some column entries,
{
"data": "day",
"type": "weekday"
},
..... the rest of the column entries
No errors in the console, however, sorting just defaults to the regular alphabetical sorting when I sort by clicking on the column title.
Sorting in DataTables is based on the detected type of the data column (you can add your own type detection functions, or override automatic detection using sType ). With this specific type given to the column, DataTables will apply the required sorting function.
By far the most commonly used of these two types is "type based sorting" and is the one you are most likely to want to use if just starting out with DataTables. How to use type based sorting plug-ins - sorting based on the sType of the column.
When the data is read in form the original table (or from any other data source) DataTables will cache this data in order to optimise sorting, filtering and other functions it provides. This is perfect for the type based sorting method where you have a static string and want to sort the information in it, which is where the first API is applied.
You can easily achieve it by writing a custom sort function. Worth putting the plug-in code before it could potentially be used. It depends what happens with the document ready function (it might execute immediately depending on code organisation, in which case an error would result). But that's the only thing I've got to add :-)
Got this working with dataTables 1.10.0-beta.2:
$(function() {
$('#datatable').DataTable({
"oLanguage": {
"sSearch": "Filter Data"
},
"iDisplayLength": -1,
"sPaginationType": "full_numbers",
"aoColumns": [{
"sType": "weekday"
},null]
});
});
Note that i just defined a type in aoColumns. The actual sorting is still done by your code.
Look at this Plunk and tell me if this is what you wanted. (Tested on Chrome cuz FF is a little bit picky when it comes to dataTables and Plunker)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With