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?
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.
The issue is related to the fact that several parts of the codebase use rows[0] to determine 1) total number of columns, 2) the parser type to use per column (eg "text" vs "digit").
Until this bug gets fixed, here is an easy workaround:
<tr class="fake_row"><td>fake</td><td>123</td></tr>
tr.fake_row { display: none; }
This seems to work effectively, allowing tablesorter to initialize and run error-free and has no impact on the rendered output.
A more generic approach would be to override the tablesorter plugin itself to check for empty tables (until they fix the issue). See this post on overriding jquery core methods: http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm
(function () {
// Store a reference to the original tablesorter plugin.
var originalTableSorter = jQuery.fn.tablesorter;
// Define overriding method.
jQuery.fn.tablesorter = function () {
if (this.find('tbody tr').size() == 0) {
if (typeof console != "undefined" && console.log) {
console.log('skipping tablesorter initialization - table is empty');
}
return;
}
// Execute the original method.
originalTableSorter.apply(this, arguments);
}
})();
This has been fixed in the lastest tablesorter (see issue 95).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With