Lightheaded Lightheaded - 1 month ago 10
Javascript Question

TableSorter doesn't recognize numbers

I have these two examples, which both use the same code but different sources of tablesorter. However one of them works as the other one doesn't.

$("table").tablesorter();


http://jsfiddle.net/lightheaded/x78cd/ (doesn't work)

http://jsfiddle.net/lightheaded/RYL54/ (works)

It should first sort by percent and then by users. However it doesn't recognize the second number to be a number. I have a similar situation on my site. What could be the issue? I'm using 2.14.4 min on my site as well.

Answer

Upgrade to a more recent version of table sorter. Recent version seems to parse out tokens from strings such as 99% coverage (12.08 million users) and 99% coverage (10.2 million users) and compare them one by one so strings that contain more than one number still sort out as expected (we have 10 compared with 12 in the above example).

OR: you can create a custom parser that normalizes the percentage and users; and use it:

$.tablesorter.addParser({
    id: 'percentThenUsers',
    is: function (s) {
        return false;
    },
    format: function (s) {
        // "99% coverage (12.08 million users)" gets converted to
        // "1099 1012.08" which can then be sorted as text
        var m = s.replace(/[^\d\.]/g, " ").replace(/ +/g, " ").split(" ");
        return (+m[0] + 1000) + " " + (+m[1] + 1000);
    },
    type: 'text'
});

$(function () {
    $("table").tablesorter({
        debug: true,
        headers: {
            0: { sorter: 'percentThenUsers' }
        }
    });
});

Demo here

Comments