Ten Digit Grid
Ten Digit Grid

Reputation: 2679

jquery table sorting with plugin

I am using a jquery plugin found at:

http://tablesorter.com/docs/

I was able to get it to work on a static table. But now I am trying to get it to work on a table that is filled from a database with ajax. I feel am putting this code:

    $(document).ready(function(){ $("#myTable").tablesorter(); } ); 

in the wrong spot. I just have it in Javascript tags at the top of the page. Since the table keeps getting refreshed I think I might need to call the above code again. Should it go in the ajax call or what?

Upvotes: 1

Views: 3758

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Yes, you should execute it inside the ajax success handler where you create the dynamic table. It is because jQuery should be able to find the element on the page before applying the plugin on it. Since you are creating it dynamically it will not find it if you execute the code on document ready.

$.ajax(function(){
   ..
   success: function(){
        //Other code to create the dynamic table
        $("#myTable").tablesorter();
   }
   ..
});

Update:

If you are emptying the existing rows and just refreshing the same table with new rows(data) then you have to trigger update event on the table.

$("myTable").trigger("update"); 

Upvotes: 3

mgibsonbr
mgibsonbr

Reputation: 22017

Check your plugin documentation, there's probably a way to re-sort it after the data has changed. This example might be what you're looking for. It creates the table sorter once, with empty data. When the data is inserted, it triggers an update using:

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

This is the code you should use after each ajax call. Your original code should remain as it is (run it only once). The complete example would be something like:

$(document).ready(function(){ 
    $("#myTable").tablesorter();
    $.ajax(function(){
        ..
        success: function(){
            // Update your table data (remove and insert tr, tds etc)
            $("#myTable").trigger("update");
            // If your sorting conditions changed, use also:
            $("#myTable").trigger("sorton",[sortingConditions]);
        }
        ..
    });
});

(Fragments of code copied from yours and ShankarSangoli's answers)

Upvotes: 1

Related Questions