Reputation: 1080
Is it possible for http://tablesorter.com to sort on different values depending on whether the sort is ascending or descending ?
I see how to return sort values for a cell based on arbitrary data with a parser (i.e.: http://code-cocktail.in/hidden-value-sorting-in-jquery-tablesorter-plugin/ ) , so returning different values in different situations seems simple enough.
The bit I'm banging my head on is that I cannot seem to determine the sort order when parsing. It looks like I can re-parse cells when a sort is being requested via the following:
$(".tablesorter").bind("sortStart",function() {
$(".tablesorter").trigger("update");
});
... however it looks like at the "sortStart" point the order of the sort isn't known, so the parser cannot provide different values based on that column's sort order.
Is this possible ? Thanks :-)
Upvotes: 1
Views: 1036
Reputation: 86403
For the following code to work, you'll need to use my fork of tablesorter which has css, widgets and addons that are not compatible with the original version.
This is somewhat similar to this Stackoverflow question except that it allows sorting one column using two different values (both answers work nicely using different methods).
A minor modification is required to use one value during ascending sort and another during descending sort (demo):
HTML (one cell)
<th class="gamename">
<span class="name">Fun Fun</span>
<span class="perc">96%</span>
</th>
Script
$(function () {
$('#games').tablesorter({
theme: 'blue',
textExtraction: {
0: function (node, table, cellIndex) {
var $n = $(node);
// add semi-colon between values
return $n.find('.name').text() + ';' + $n.find('.perc').text();
}
},
textSorter: function (a, b, direction, columnIndex, table) {
if (columnIndex === 0) {
var c = table.config,
x = a.split(';'),
y = b.split(';'),
// sort column by percentage when descending sort is active
i = c.$headers.eq(0).hasClass('tablesorter-headerDesc') ? 1 : 0;
return $.tablesorter.sortNatural($.trim(x[i]), $.trim(y[i]));
} else {
return $.tablesorter.sortNatural(a,b);
}
}
});
});
Upvotes: 2