I’ve recently been using a lot of the jQuery tablesorter plugin across many tables containing many different types of data. It’s a great plugin, but occasionally its documentation can be a little lacking in parts.
One of the first useful things you might want is the list of inbuilt data types that it handles. Most of the time these will be auto detected, however sometimes you’ll need to specify them manually (either in your jQuery, or by adding some markup to your table header, i.e. <th class="{sorter: false}"> ).
Here’s the list of built in data types:
- text
- integer
- currency
- floating
- ipAddress
- url
- isoDate
- percent
- usLongDate
- shortDate (which has options of UK, US, and dd/mm/yyyy)
- time
I found the list originally here: jQuery Tablesorter: List of Builtin Parsers/Sorters @ terminally-incoherent.com, which doesn’t mention the UK/US options, which could have been added to the plugin since the post was made. The shortDate variants can be used directly, i.e. class="{sorter: 'uk'}" in the table header tag.
Another thing to note if you’re trying to use the inline option syntax above (i.e. <th class="{sorter: false}"> ) to set sorting options is that you need to be using the jQuery metadata plugin. Now, this IS in the tablesorter documentation, but somehow I managed to miss it.
Finally, Norwegian dates are in dd.mm.yyyy format, which is a useful excuse to throw in a quick example of how to add a custom parser:
$.tablesorter.addParser({
id: 'dd.mm.yyyy',
is: function(s) {
return false;
},
format: function(s) {
s = '' + s;
var hit = s.match(/(\d{1,2})\.(\d{1,2})\.(\d{4})/);
if (hit && hit.length == 4) {
return hit[3] + hit[2] + hit[1];
}
else {
return s;
}
},
type: 'text'
});
The other one I needed was for comma separated numbers, so here’s what that one looks like:
$.tablesorter.addParser({
id: "commaNum",
is: function (s) {
return false;
},
format: function (s) {
return s.replace(/,/g, '');
},
type: 'numeric'
});
Happy sorting!
Tags: jQuery, Web Development