23

I am using the jQuery tableSorter plugin on a page.

Unfortunatley, the table that is being sorted is dynamically modified, and when I sort after adding an element, the element disappears, restoring the table to the state that it was in when the tableSorter was created.

Is there any way that i can force tableSorter to rescan the page so that these new elements are sorted properly?

4 Answers 4

26

I believe you can trigger an update using something like:

$(table).trigger("update")
Sign up to request clarification or add additional context in comments.

1 Comment

Just a comment, i need to use the code like this: $("#table_id").trigger("update");
14

Seems you are correct.

$(table).trigger("update");
$(table).trigger("appendCache");

does the trick.

As a note, the tablesorter API changed at some point, so these things got changed, as well as the event binding. My biggest hangup was trying to figure out why some things worked and others did not, and it was due to having a wrong version of the plugin, despite there being no obvious distinction.

2 Comments

This should be the accepted answer. Without the "appendCache" part, I can only sort in one direction (1st click sorts, 2nd does nothing), as in Josh's answer. But with it, everything works as expected. Note that if the update is occurring in another code block from where you created your tablesorter object, you can just recreate it there. Suppose your tablesorter tabe has id "ts". Do $("#ts").tablesorter().trigger("update"); and same for appendCache. Or: $table = $("#ts").tablesorter(); $table.trigger("update"); $table.trigger("appendCache");
On the other hand, I just found out that this answer will not work if you just deleted a row. I'm not sure you actually need to do anything if you delete a row.
4

The $(table).trigger("update"); throws error

    Uncaught TypeError: Cannot read property 'rows' of undefined 

So, there is a jquery function .ajaxStop() where tablesorter() is called. Do not call tablesorter in .ready()

    jQuery(document).ajaxStop(function(){
      jQuery("#table_name").tablesorter();
    })

which did the job

Comments

2

For those Newbies like me who are facing issue with sorting dynamic generated table, here is the solution. The answer previously given are correct, but where do you place this command?

$('#tableId').tablesorter().trigger('update');

You need to place it as soon as you've appended the data to the table. Ex in my case

var tableData = "<thead><tr><th>Name</th><th>Age</th></thead><tbody><tr><td>Izaki</td><td>24</td><tr><tr><td>Serizawa</td><td>25</td></tr>";
$('#tableId').html('tableData');
$('#tableId').tablesorter().trigger('update');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.