Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery TableSorter Plugin error on init : cannot read property '0' of undefined

i wanna sort my table with jQuery Plugin TableSorter . So i get this table :

<table id="stats" class="zebra-striped">
 <thead>
  <tr>
   <th>Date</th>
   <th>Annonce</th>
   <th>Support</th>
   <th>Nb Assoc.</th>
   <th>Nb Transfo.</th>
   <th>Cout</th>
  </tr>
 </thead>
 <tbody>
 </tbody>
</table>

So as you can see my table is empty, just had header. So i init tablesorter with empty cell with :

$("table#stats").tablesorter({ sortList: [[0,0]]});

and immediatly i get this error :

jquery.tablesorter.min.js:4 Uncaught TypeError: Cannot read property '0' of undefined

FYI , there's my js loaded :

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>
<script src="js/bootstrap-dropdown.js"></script>
<script src="js/bootstrap-scrollspy.js"></script>
<script src="js/jquery.tablesorter.min.js"></script>

Any idea why i get this and how i can make the plugin work again ?

Thx

like image 650
Clawfire Avatar asked Jan 16 '12 10:01

Clawfire


4 Answers

You need to have data in your table before you can call the sortList method on it. This is because you apply an indexing in this method that will not find any records if there is no data present and that will throw the "Cannot read property '0' of undefined" error.

like image 169
JoJa Avatar answered Nov 16 '22 05:11

JoJa


It's not good use tablesorter when there is a empty table, so you can use this condition:

if ($("table#stats tbody tr").length > 0)
   $(this).tablesorter({ sortList: [[0,0]]});
like image 41
Michael Aguilar Avatar answered Nov 16 '22 06:11

Michael Aguilar


You don't need to have data in your table. Just initilize your table that way:

$("table#stats").tablesorter();

Then, after you have inserted the data in the table, you must tell to plugin that the table was updated and sort it:

$("table#stats").trigger("update");
var sorting = [[0,0]];
$("table#stats").trigger("sorton",[sorting]);
like image 9
Eneas Gesing Avatar answered Nov 16 '22 06:11

Eneas Gesing


I couldn't get any of this to work so I set a timeout on the initialize for tablesorter...

setTimeout(function() {$('table').tablesorter();}, 10000);
like image 4
Amaan Avatar answered Nov 16 '22 07:11

Amaan