Sorting tables dynamically with javascript is often a smooth solution to your sorting problems. I’m here going to put a simple solution that I have been using for a while. I have in no means created this solution – I found it somewhere on the web and now I just want to put it here for easy access.
The table needs to have the following structure for this solution to work:
column1 | column2 | column3 |
---|---|---|
value1 | value2 | value3 |
value4 | value5 | value6 |
value7 | value8 | value9 |
The critical parts here is that the table needs an id and a tbody. Without those the sorting will not work
Here is the JQuery code (standard JQuery, no plugins needed)
function sortTable(){ var rows = $('#mytable tbody tr').get(); rows.sort(function(a, b) { var A = $(a).children('td').eq(1).text().toUpperCase(); var B = $(b).children('td').eq(1).text().toUpperCase(); if(A < B) { return -1; } if(A > B) { return 1; } return 0; }); $.each(rows, function(index, row) { $('#mytable').children('tbody').append(row); }); }
To sort according to the second column we use ‘.eg(1)’ in row 6 and 7. Second column ‘.eg(3)’ and so on
Here is a JSFiddle of the solution: JQuery sort table rows on column value
Tested on Chrome v44.0.2403.155 (64-bit) and JQuery 1.9.1