DLeh
DLeh

Reputation: 24395

JQuery table sorter doesn't work with date range string

I have a column in my table that shows variations of the following text, where the dates vary

Requested Statement 7/1/2014 - 9/16/2014

tablesorter has trouble sorting this properly, as you can see in this fiddle. The first column will sort when clicked, but the second will not. I also included a table of some string comparisons to show that javascript properly recognizes the order they should be in.

http://jsfiddle.net/kfu4ragh/1/

I tried adding a custom textExtraction function but I'm still getting the same results.

It seems that tablesorter is doing something different than a simple > or < to determine the order of the string values. Is there a way I can alter tablesorter to sort this column correctly?

Upvotes: 1

Views: 317

Answers (1)

Mottie
Mottie

Reputation: 86413

The problem is that the second column ("Requested Statement...") is being detected as a date column and the parser is trying to turn that entire string into a date; which is invalid.

Here is a demo with the relevant extracted out functions from tablesorter. The result is:

// start with "Requested Statement 7/1/2014 - 9/16/2014"
"Requested Statement 2014/7/1 / 9/16/2014" => 0

So you'll need to use the textExtraction function to target the date (demo):

$('table').tablesorter({
    textExtraction : function(node){
        var txt = $(node).text();
        if (/request/i.test(txt)) {
            // return the 3rd block (first date in range)
            txt = txt.split(' ')[2];
        }
        return txt;
    }
});

Note that the second date in the string is completely ignored. If you would like to make the second date matter, try this code (demo):

$('table').tablesorter({
    textExtraction : function(node){
        var d1, d2,
            txt = $(node).text();
        if (/request/i.test(txt)) {
            // return the 3rd block (first date in range)
            txt = txt.split(' ');
            d1 = $.tablesorter.formatFloat(new Date(txt[2]).getTime());
            d2 = $.tablesorter.formatFloat(new Date(txt[4]).getTime());
            // add the times together - there is likely a better
            // method but this works in this situation
            txt = d1 + d2;
        }
        return txt;
    }
});

Upvotes: 1

Related Questions