Bård
Bård

Reputation: 634

jquery tablesorter sorting empty table cells last

I have a table with a column with numbers spanning approximately -10 to 10 and some empty columns.

I'd like tablesorter to always put the empty columns at the bottom of the table. Even if I sort ascending or descending.

Like this:

-1
0
2
3
<empty cell>
<empty cell>

or like this:

3
2
0
-1
<empty cell>
<empty cell>

Note that my problem is the same as question 4792426 except that I want empty cells on the bottom both when sorting order is descending and ascending.

Deleting rows is not an option.

Upvotes: 5

Views: 4489

Answers (3)

Finch_Powers
Finch_Powers

Reputation: 3096

If it can help anyone, here is how I did it for text.

function emptyAtBottomTextSorter(a, b, direction, column, table) {
    if (a == "") {
        a = direction ? "ZZZZZ" : "";
    }
    if (b == "") {
        b = direction ? "ZZZZZ" : "";
    }
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}

$("#myTable").tablesorter({
    headers: {
        1 : {'sorter' : 'text'}
    },
    textSorter: {
        1 : emptyAtBottomTextSorter
    }
});

Working as of Tablesorter v2.26.2

Upvotes: 0

J Gommans
J Gommans

Reputation: 21

With later versions of tablesorter jQuery plugin you can add a different kind of sorter in the headings to automatically put empty/null or string (if for example you enter a "-" in place of null) where you'd like (top/bottom).

<th class="{'sorter': 'digit', 'string': 'bottom'}">Count</th>

This is a way to embed it directly into html/templates. But if you have consistency in your column count you can do it in the initial tablesorter function.

$('table').tablesorter(
    headers: {
       1: { sorter: "digit", empty : "top" },
       2: { sorter: "digit", string: "bottom"}
    }
)

Either way works fine but it basically forces whatever you put as the second k,v of the header object to take precedence over sorting in the normal fashion.

More information can be found in the tablesorter docs.

Upvotes: 2

B&#229;rd
B&#229;rd

Reputation: 634

I found a way to solve my problem.

The solution provided by ssell did not work. The table data is parsed only once, so you cannot use a global variable to control it. Nice try though! :-)

This is the code needed. As you see I overload the formatFloat and formatInt functions so that they return null instead of the default value: 0. The sorting function inside tablesorter does the rest magically for me.

        $(document).ready(function () {
        $.tablesorter.formatInt = function (s) {
            var i = parseInt(s);
            return (isNaN(i)) ? null : i;
        };
        $.tablesorter.formatFloat = function (s) {
            var i = parseFloat(s);
            return (isNaN(i)) ? null : i;
        };
        $("#table").tablesorter();
    });

As far as I know my solution is undocumented, but it works fine.

Upvotes: 7

Related Questions