Suppose I have a table with the fields 'Rank', 'Id' and 'Name'. When you click "Rank", the table is sorted by rank in ascending order using this code
$(function(){ $("#rank").click(function(){ var rows = $("#rank_table tbody tr").get(); rows.sort(sortTable); $.each(rows, function(index, row){ $("#rank_table").children("tbody").append(row); }); }); }); function sortTable(a,b){ var A = parseInt($(a).children('td').eq(0).text()); var B = parseInt($(b).children('td').eq(0).text()); if (A < B) return -1; if( A > B) return 1; return 0; }
The rank and identifier are integers with the identifier 'rank' and 'st_id', respectively. So what I want to achieve is that when I click on the Rank field once, the table is sorted in ascending order and clicks again, it sorts the table in descending order. I want to do this for both fields of rank and Id.
For descent, I need to use a function other than the upstream of this upstream function. How can I achieve this using the jquery and this () function (not plugins)? Thanks at Advance.
Here is the html
<!Doctype html> <html> <head> <style> #thead { cursor: pointer; text-decoration: underline; text-align: center; } #tbody { text-align: center;} </style> <script src="libs/jquery-1.5.1.js" type="text/javascript"></script> <script src="table_sort.js" type="text/javascript"></script> </head> <body> <table id="rank_table"> <thead id="thead"> <tr> <th id="rank">Rank</th> <th id="st_id">Student_id</th> <th id="st_name">Name</th> </tr> </thead> <tbody id="tbody"> <tr> <td>3</td> <td>2</td> <td>Ted</td> </tr> <tr> <td>2</td> <td>1</td> <td>John</td> </tr> <tr> <td>5</td> <td>4</td> <td>Neil</td> </tr> <tr> <td>1</td> <td>5</td> <td>Alex</td> </tr> <tr> <td>4</td> <td>3</td> <td>Nave</td> </tr> </tbody> </table> </body> </html>
Alonso
source share