'Client side sorting with html and Javascript
How can I make a html table which the user can sort using the column headers to sort on the client side? I can load all rows' html data into a Javascript array and use dom to add a table to a content div but is it the right way? If you list major methods, I can find my way from there so, I'm not asking for code.
Solution 1:[1]
http://tinysort.sjeiti.com/ should be usefully
Solution 2:[2]
No need to reinvent the wheel in case you utilise a JS Framework already, but here are quite some nice solutions:
TableSort - http://www.frequency-decoder.com/demo/table-sort-revisited/
JQuery tablesorter - http://tablesorter.com/docs/#Demo
GridView3 - http://dev.sencha.com/playpen/ext-2.0/examples/grid/grid3.html
Stuart Langridge's Script - http://yoast.com/articles/sortable-table/
Mootools Mootable - http://joomlicious.com/mootable/
Solution 3:[3]
tablesorter is good, but you want something that has filtering built in, and is pretty widely used and supported try http://datatables.net/
Solution 4:[4]
Every tablesorter works like this:
- get the
table.tbody.rowsin an array - sort that array using a custom compare function
- append the rows to the table body in the correct order
It is usually be a bit faster if you precompute the values-to-compare (instead of accessing the DOM elements on every comparison), the array would then contain objects that have the value in one slot and the table row element in the other.
Solution 5:[5]
If you have an array, then calling sort() is probably your best bet:
function sortArray(a, b){
//could also say return a-b instead of the blown out if...else construct
if(a.Age===b.Age) { return 0; }
else if (a.Age < b.Age) { return -1; }
else { return 1; }
}
var rows = [{Name: 'Amy', Age: 10}, {Name: 'Bob', Age: 20}];
var sortedArray = rows.sort(sortArray);
As the other answers have stated, you can also use a plug-in. DataTables is a good one that I've used in the past.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sender |
| Solution 2 | |
| Solution 3 | mkoryak |
| Solution 4 | Bergi |
| Solution 5 | David Hoerster |
