Rachel G. Rachel G. - 1 month ago 27
jQuery Question

Using jQuery Tablesorter with Column Spans

I am using the jQuery tablesorter plugin to sort a table with 14 columns. However, every once in awhile I need to insert a row that spans all 14 columns. But this seems to break the sorting functionality (only the first column sorts, all the others are broken).

The JavaScript error says jquery.tablesorter.js is failing on this return statement:

function getCachedSortType(parsers,i) {
return parsers[i].type;
};


Does anyone know how to get the sorting to ignore a row?

Here is my current code (I am not sorting the first 2 columns just to simplify things):

$("#myTableId").tablesorter({
textExtraction: function(node){
var cellValue = $(node).html();
return (cellValue == null ? "" : cellValue);
},
headers: {
0: {sorter:'text'},
1: {sorter:'text'},
2: {sorter: false},
3: {sorter: false},
4: {sorter: false},
5: {sorter: false},
6: {sorter: false},
7: {sorter: false},
8: {sorter: false},
9: {sorter: false},
10: {sorter: false},
11: {sorter: false},
12: {sorter: false},
13: {sorter: false}
}
});

Answer

There is a plugin for the plugin:

https://github.com/ascii-soup/Tablesorter-Static-Row-Plugin

The alternative is that using the sortStart and sortEnd bindings in the tablesorter plugin, you have a function that removes the column spanning rows before the sort and a function that adds them back in after the sort. The plugin above doesn't work with rows spanning all the columns, so a combination of the two is required.

This is one way of doing it - temporarily remove the colspan and add columns before the sort and undo the changes after the sort (assumes the rows that span all columns have class fullSpan):

$("#myTableId").bind("sortStart",function() { 
        var colCount = getColCount();
        $('tbody .fullSpan').each(function() {
            $(this).removeAttr('colspan');
            for (var i= 0; i < colCount; i++) {
                 $(this).append('<td class="temptd"></td>');
            }
        }); 
}).bind("sortEnd",function() { 
        var colCount = getColCount();
        $('.temptd').remove();
        $('tbody .fullSpan').each(function() {
                 $(this).attr('colspan', colCount);
        });
}); 

You can combine this with the static row plugin if you want (adding the widget and a static class).

Have a look at this jsfiddle: http://jsfiddle.net/DrZgM/20/

P.S. static row plugin has a bug with latest JQuery - has been embedded into JSfiddle above.