Search code examples
javascriptjqueryexceptiontablesorter

jQuery + TableSorter: Error when table is empty


jQuery's plugin TableSorter doesn't seem to handle a situation where it is attached to an empty table. Is there a neat way around this?

In my application the user can filter and search the data and eventually he or she will come up with a search criteria which doesn't return any values. In these situations it would be nice to "detach" the TableSorter or somehow fix it's code so that it works with an empty table.

I'm currently using the plugin like this:

    $("#transactionsTable")
    .tablesorter({ widthFixed: true, widgets: ['zebra'] })
    .tablesorterPager({ container: $("#pager"), positionFixed: false });

This works well, until the table is empty. Then I get the following error:

Line: 3
Error: '0.length' is null or not an object

Any ideas? Is it possible to change the script so that the tablesorter is only added to the table if it has rows?


Solution

  • I think you can do it for your self.

        if ($("#transactionsTable").find("tr").size() > 1)
        {
              //> 1 for the case your table got a headline row
              $("#transactionsTable")
              .tablesorter({ widthFixed: true, widgets: ['zebra'] })
              .tablesorterPager({ container: $("#pager"), positionFixed: false });
        }
    

    If your table got a tbody tag it is easier:

    if ($("#transactionsTable").find("tbody").find("tr").size() > 0)
    

    This way is maybe not the most professional one, but it should work under this circumstatances.