سؤال

I need to sort numbers in column so that negative numbers always sorted under positive numbers. Read that it can be done with help of numberSorter property but I don't find any example with it. For example wen I sort ascending it sorts like this:
1
2
3
4
5
6
-1
-2
-3
And when I sort descending it sorts like this:
6
5
4
3
2
1
-3
-2
-1

Their example:

$(function(){
    $("table").tablesorter({
        numberSorter : function(a, b, direction, maxColumnValue){
            // direction; true = ascending; false = descending
            // maxColumnValue = the maximum value of that column (ignoring its sign)
            return a - b;
        }
    });
});

gives me error: TypeError: x is undefined

How can I do it?

هل كانت مفيدة؟

المحلول

Well, it looks like you found a bug. This line (732):

sort = c.numberSorter ? c.numberSorter(x[col], y[col], dir, colMax[col], table) :

should actually look like this (replace x & y with a & b, respectively)

sort = c.numberSorter ? c.numberSorter(a[col], b[col], dir, colMax[col], table) :

Then once you do that you can use this numberSorting script (demo).

$("table").tablesorter({
    theme : 'blue',
    numberSorter: function (a, b, direction) {
        if (a >= 0 && b >= 0) { return direction ? a - b : b - a; }
        if (a >= 0) { return -1; }
        if (b >= 0) { return 1; }
        return direction ? b - a : a - b;
    }
});

نصائح أخرى

   // add parser through the tablesorter addParser method 
    $.tablesorter.addParser({ 
        // set a unique id 
        id: 'mySortingFunction', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) { 
            // your logic
            return s; 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    }); 

$(function() { 
    $("table").tablesorter({ 
        headers: { 
            6: { 
                sorter:'mySortingFunction' 
            } 
        } 
    }); 
});                  

6 it's the column number you want to sort with custom mySortingFunction (you'll need to change it).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top