3

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.

5 Answers 5

3

http://tinysort.sjeiti.com/ should be usefully

Sign up to request clarification or add additional context in comments.

Comments

3

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/

Comments

2

tablesorter is good, but you want something that has filtering built in, and is pretty widely used and supported try http://datatables.net/

Comments

2

Every tablesorter works like this:

  1. get the table.tbody.rows in an array
  2. sort that array using a custom compare function
  3. 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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.