HTML Table Sorting Using JavaScript

One of the most common actions when viewing data in a tabular format is to be able to sort. With DHTML and JavaScript, it’s possible to sort the data on the clientside. This avoid unnecessary roundtrip to the server and improves the usability. There are a few javascript libraries that provide the sorting capability with minimal edits to the html. However, if you want to have a total control over the sorting, for features such as, sorting a column sorts against data that is different than what’s visible (for example, data is displayed as percentages while the sorting is done without the % symbol, data is displayed as yyyy/mm/dd but internally there is a date object corresponding to what is displayed), then more control is required on sorting the data. Below is a snippet of code for doing this.


function DataRow(data) {
this.data = data; // data is itself an array or other object that contains data
this.row = null;
}

var data = new Array();
// here generate/write javascript to store the rows and their data, for example,
// data[data.length] = new DataRow(new Array(1,2,3));

var table = document.getElementById('data'); // assuming there is no THEADER
if(table.firstChild.nodeName == 'TBODY') table = table.firstChild;
var rows = table.getElementsByTagName('TR');
for(var i=1;i<rows.length;i++) // assuming header is also stored as a row
data[i].row = row[i];

function sortTable(event,col) {
var header = table.firstChild; // storing both heading and data in tbody.
while(table.firstChild) table.removeChild(table.lastChild);
table.appendChild(header);
data.sort(function(a,b) { return a.data[col] - b.data[col]; });
// you can have more complex logic based on the data and requirements
for(var i=0;i<data.length;i++)
table.appendChild(data[i]);
}

Next, it’s a matter of pluging in the sortTable(event,col) call in the onclick of the header.

The key idea here is to be able to keep the data and the related UI element (the row), together as an object and do sorting on those objects.

Advertisements

Leave a comment

Filed under DHTML, javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s