I have a few tables on my webpage where I use the tablesorter extension to allow sorting. Everything works fine except for one table. This particular table contains a numeric value, but also a div element. The problem is, that since there is the div, the tablesorter treats it as text and for example "1000" is sorted as lower than "999", because it only recognizes the initial 1 and 9.
I have read the documentation and tried to implement a custom parser based on it - http://tablesorter.com/docs/example-parsers.html
Unfortunately it doesnt work. Basically what I was trying to achieve - the cell always contains a number followed by "...... " etc. so I was trying to filter out the value in front of the initial "<" symbol. But for some reason it just ignores the parser.
It is difficult to explain properly, so I have created a jsfiddle. Please ignore the rest of the design, images etc. it looks differently on my page, but the issue is there.
Look at for example the column "Total", there are numbers larger than 1000 but it is sorted as lower than numbers above 100 (it is obviously treated as text). The sorting is initialized by clicking on the table headers.
Any help appreciated. http://jsfiddle.net/8v8ycb09/
Parser code:
$.tablesorter.addParser({
// set a unique id
id: 'main',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format your data for normalization
return s.substr(0, s.indexOf('<'));
},
// set type, either numeric or text
type: 'numeric'
});
If I understand correctly, you just need to return parseInt(s)
from the format function.
parseInt()
ignores initial whitespace and anything after a leading numeric string.
format: function (s) {
// format your data for normalization
return parseInt(s);
},
And apply the custom sorter to columns as follows :
$(function () {
var sMap = {sorter:'main'};
$("#rTable").tablesorter({
headers: {
2: sMap,
3: sMap,
4: sMap,
5: sMap,
6: sMap,
7: sMap,
8: sMap,
9: sMap,
10: sMap,
11: sMap,
12: sMap,
13: sMap,
14: sMap,
15: sMap,
16: sMap
}
});
});