Search code examples
jquerysortingtablesorter

how can i store a sort using jquery tablesorter?


I am using jquery tablesorter. I can sort all the columns, but i want to store a sort type next time i visit the page. how can i do that? because i also want to sort the table in ascending order when loaded, lets suppose for the first time or if the sort is not made.

Following is my code.

 <script>
 $(document).ready(function() { 
// call the tablesorter plugin 
$("table").tablesorter({ 
    // change the multi sort key from the default shift to alt button 
    sortMultiSortKey: 'altKey' 
    }); 
}); 

</script>

The HTML is the following

 <table cellspacing="1" class="tablesorter">             
<thead>> 
    <tr> 
        <th>first name</th> 
        <th>last name</th> 
        <th>age</th> 
        <th>total</th> 
        <th>discount</th> 
        <th>date</th> 
    </tr> 
</thead> 
<tbody> 
    <tr> 
        <td>peter</td> 
        <td>parker</td> 
        <td>28</td> 
        <td>$9.99</td> 
        <td>20%</td> 
        <td>jul 6, 2006 8:14 am</td> 
    </tr> 
    <tr> 
        <td>john</td> 
        <td>hood</td> 
        <td>33</td> 
        <td>$19.99</td> 
        <td>25%</td> 
        <td>dec 10, 2002 5:14 am</td> 
    </tr> 
    <tr> 
        <td>clark</td> 
        <td>kent</td> 
        <td>18</td> 
        <td>$15.89</td> 
        <td>44%</td> 
        <td>jan 12, 2003 11:14 am</td> 
    </tr> 
    <tr> 
        <td>bruce</td> 
        <td>almighty</td> 
        <td>45</td> 
        <td>$153.19</td> 
        <td>44%</td> 
        <td>jan 18, 2001 9:12 am</td> 
    </tr> 
    <tr> 
        <td>bruce</td> 
        <td>evans</td> 
        <td>22</td> 
        <td>$13.19</td> 
        <td>11%</td> 
        <td>jan 18, 2007 9:12 am</td> 
    </tr> 
</tbody> 


Solution

  • I can't tell if you are using the origin tablesorter (v2.0.5) or my fork of tablesorter. Either way, you need to set the sortList option apply an initial sort to a table

    $(function(){
      $("table").tablesorter({
        sortList : [[1,0], [2,1]] // initial sort columns (2nd and 3rd)
      });
    });
    

    The sortList uses this format:

    [[columnIndex, sortDirection], ... ]
    
    • columnIndex is a zero-based column index.
    • sortDirection set to 0 (zero) applies an ascending sort, and 1 (one) applies a descending sort to the column.
    • Add multiple column sorts as an array within an array. So the above example will apply an ascending sort to the second column then apply a descending sort to the third column.