tablesorter
tablesorter copied to clipboard
Custom sort functions
It would be great to have possibility to define custom sort (compare) functions. I'm using tablesorter in my recent app, but table that it sorts contains values that are not sorted correctly by default. I need a way to sort non-ascii characters and bring empty cells down to the end of a table.
@Arrvi http://tablesorter.com/docs/example-parsers.html you can add custom parser
In my fork of tablesorter, there is an emptyTo
option which allows defining where to sort empty cells - check out this demo.
Unfortunately, it is not possible to add an "autodetecet" sorter, which will be checked before the standard validators.
Example:
ts.addParser({
id: "germanShortDate",
is: function (s) {
return /\d{1,2}[\.]\d{1,2}[\.]\d{2,4}/.test(s);
}, format: function (s, table) {
s = s.replace(/(\d{1,2})[\.](\d{1,2})[\.](\d{2,4})/, "$3/$2/$1");
return $.tablesorter.formatFloat(new Date(s).getTime());
}, type: "numeric"
});
Value: "01.01.2014"
The used parser is: digit :-(
It will be great, if there is a method like: addUserParser() and this parsers will be checkt before the standard
like: unshift
this.addUserParser = function (parser) {
var l = parsers.length,
a = true;
for (var i = 0; i < l; i++) {
if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
a = false;
}
}
if (a) {
parsers.unshift(parser);
};
};
Hi @tombrain!
Unfortunately, it is not possible to add an "autodetecet" sorter, which will be checked before the standard validators.
Yes, it is... that's the purpose of the is
callback function (docs). And all custom parsers are checked before the built-in parsers – look at the code in detectParserForColumn
.
If you don't want to use a regular expression in the is
callback, you could check the column index (if the table doesn't contain any colspans):
$.tablesorter.addParser({
id: 'myparser',
is: function(s, table, cell, $cell) {
// Auto-enable this parser for the 3rd column
return cell.cellIndex === 2;
},
format: function(s, table, cell, cellIndex) {
// do something to "s"
return s;
},
parsed: false,
type: 'numeric'
});