Table
ID |
NAME |
Value |
SPECIALIZATION
|
Row Header 1 | 1 |
1 | Angelina | -1 | Computer Science |
Row Header 2 | 2 |
2 | Martina | 10 | Mathematics |
Row Header 3 | 3 |
3 | Tina | 0.5 | English |
Row Header 4 | 4 |
4 | Simran | 100 | Biology |
Row Header 5 | 5 |
5 | Christina | -99 | Psychology |
The code below allows the above table to sort the data values while keeping the row headers above.
Something i couldn't find an example for on Google.
function doSort(column, tableID, direction) {
var data = []
var table = document.getElementById(tableID);
var skip = 1; // skip column headers
// set up sortable data array [ sorted key, row data, header data ]
for (var i = skip + 1, l = table.rows.length; i < l; i=i+2) {
// grab each row - so we can clone later
var header_cell_row = table.rows[i - 1]; // header cell row data
var data_row = table.rows[i]; // sortable row data
var cell_data = table.rows[i].cells[column].innerHTML; // this is the bit we sort.
data.push([parseFloat(cell_data), data_row, header_cell_row])
};
//sort that array in the direction we ask
data.sort(
direction==0 ?
function(a,b){return a[0]<b[0]?-1:a[0]>b[0]?1:0} // ASC
:
function (a, b) { return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0} // DESC
)
// run thru sorted array
for (var i = 0, l = data.length; i < l; i++) {
// we append at the bottom of the original table the new sorted table
// as we have saved the real rows we can clone and append
//
// header row
//
var source = data[i][2];
table.appendChild(source.cloneNode(true));
//
// data row
//
var source = data[i][1];
table.appendChild(source.cloneNode(true));
//
// delete an old row from the table
//
table.deleteRow(1);
table.deleteRow(1);
}
}