DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
Google Visualizations is another option, but requires a bit more setup that dataTables, but does NOT require any particular framework/library (other than google.visualizations):
And there are other options to... especially if you're using one of the other JS frameworks. Dojo, Prototype, etc all have usable "table enhancement" plugins that provide at minimum table sorting functionality. Many provide more, but I'll restate...I've yet to come across one as powerful and as FAST as datatables.net.
You could deal with a json array and the sort function. It is a pretty easy maintanable structure to manipulate (ex: sorting).
Untested, but here's the idea. That would support multiple ordering and sequential ordering if you pass in a array in which you put the columns in the order they should be ordered by.
var DATA_TABLE = {
{name: 'George', lastname: 'Blarr', age:45},
{name: 'Bob', lastname: 'Arr', age: 20}
//...
};
function sortDataTable(arrayColNames, asc) { // if not asc, desc
for (var i=0;i<arrayColNames.length;i++) {
var columnName = arrayColNames[i];
DATA_TABLE = DATA_TABLE.sort(function(a,b){
if (asc) {
return (a[columnName] > b[columnName]) ? 1 : -1;
} else {
return (a[columnName] < b[columnName]) ? 1 : -1;
}
});
}
}
function updateHTMLTable() {
// update innerHTML / textContent according to DATA_TABLE
// Note: textContent for firefox, innerHTML for others
}
Now let's imagine you need to order by lastname, then name, and finally by age.
var orderAsc = true;
sortDataTable(['lastname', 'name', 'age'], orderAsc);
I wrote up some code that will sort a table by a row, assuming only one <tbody> and cells don't have a colspan.
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
// sortTable(tableNode, columId, false);
If you don't want to make the assumptions above, you'd need to consider how you want to behave in each circumstance. (e.g. put everything into one <tbody> or add up all the preceeding colspan values, etc.)
You could then attach this to each of your tables, e.g. assuming titles are in <thead>
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
The best way I know to sort HTML table with javascript is with the following function.
Just pass to it the id of the table you'd like to sort and the column number on the row. it assumes that the column you are sorting is numeric or has numbers in it and will do regex replace to get the number itself (great for currencies and other numbers with symbols in it).
function sortTable(table_id, sortColumn){
var tableData = document.getElementById(table_id).getElementsByTagName('tbody').item(0);
var rowData = tableData.getElementsByTagName('tr');
for(var i = 0; i < rowData.length - 1; i++){
for(var j = 0; j < rowData.length - (i + 1); j++){
if(Number(rowData.item(j).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, "")) < Number(rowData.item(j+1).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, ""))){
tableData.insertBefore(rowData.item(j+1),rowData.item(j));
}
}
}
}
Using example:
$(function(){
// pass the id and the <td> place you want to sort by (td counts from 0)
sortTable('table_id', 3);
});
Sorting table rows by cell.
1. Little simpler and has some features.
2. Distinguish 'number' and 'string' on sorting
3. Add toggle to sort by ASC, DESC
var index; // cell index
var toggleBool; // sorting asc, desc
function sorting(tbody, index){
this.index = index;
if(toggleBool){
toggleBool = false;
}else{
toggleBool = true;
}
var datas= new Array();
var tbodyLength = tbody.rows.length;
for(var i=0; i<tbodyLength; i++){
datas[i] = tbody.rows[i];
}
// sort by cell[index]
datas.sort(compareCells);
for(var i=0; i<tbody.rows.length; i++){
// rearrange table rows by sorted rows
tbody.appendChild(datas[i]);
}
}
function compareCells(a,b) {
var aVal = a.cells[index].innerText;
var bVal = b.cells[index].innerText;
aVal = aVal.replace(/\,/g, '');
bVal = bVal.replace(/\,/g, '');
if(toggleBool){
var temp = aVal;
aVal = bVal;
bVal = temp;
}
if(aVal.match(/^[0-9]+$/) && bVal.match(/^[0-9]+$/)){
return parseFloat(aVal) - parseFloat(bVal);
}
else{
if (aVal < bVal){
return -1;
}else if (aVal > bVal){
return 1;
}else{
return 0;
}
}
}
If you want to support IE11, you'll need to ditch the ES6 syntax and use alternatives to Array.from and Element.closest.
i.e.
var getCellValue = function(tr, idx){ return tr.children[idx].innerText || tr.children[idx].textContent; }
var comparer = function(idx, asc) { return function(a, b) { return function(v1, v2) {
return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}};
// do the work...
Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function(th) { th.addEventListener('click', function() {
var table = th.parentNode
while(table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
Array.prototype.slice.call(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(function(tr) { table.appendChild(tr) });
})
});
Comparer function breakdown
For the sake of brevity, I compacted the comparer() function. It's a little complex/hard to read, so here it is again exploded/formatted/commented.
// Returns a function responsible for sorting a specific column index
// (idx = columnIndex, asc = ascending order?).
var comparer = function(idx, asc) {
// This is used by the array.sort() function...
return function(a, b) {
// This is a transient function, that is called straight away.
// It allows passing in different order of args, based on
// the ascending/descending order.
return function(v1, v2) {
// sort based on a numeric or localeCompare, based on type...
return (v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2))
? v1 - v2
: v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
Nick Grealy's accepted answer is great but acts a bit quirky if your rows are inside a <tbody> tag (the first row isn't ever sorted and after sorting rows end up outside of the tbody tag, possibly losing formatting).
I have edited the code from one of the example here to use jquery.
It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?
Issue I had is that i'm using a different format for date: dd-mm-YY instead of the ISO one.
As I'm passing data from a .php file as a string I had to convert the string in a date then compare with ><==
Substitute the compare function
// Returns a function responsible for sorting a specific column index
// (idx = columnIndex, asc = ascending order?).
var comparer = function(idx, asc) {
// This is used by the array.sort() function...
return function(a, b) {
// This is a transient function, that is called straight away.
// It allows passing in different order of args, based on
// the ascending/descending order.
return function(v1, v2) {
// sort based on a numeric or localeCompare, based on type...
return (v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2))
? v1 - v2
: v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
with this:
var comparer = function(idx, asc) {
// This is used by the array.sort() function...
return function(a, b) {
// This is a transient function, that is called straight away.
// It allows passing in different order of args, based on
// the ascending/descending order.
return function(v1, v2) {
if(v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2)){
x = v1 - v2;
console.log(v1);
} else if(v1.includes("-")) {
var partsArray1 = v1.split('-');
var partsArray2 = v2.split('-');
var data1 = new Date(partsArray1[2],partsArray1[1],partsArray1[0]);
var data2 = new Date(partsArray2[2],partsArray2[1],partsArray2[0]);
if(data1>data2){
x=1;
} else if (data1<data2) {
x=-1;
} else if (data1==data2) {
x=0;
}
} else {
x = v1.toString().localeCompare(v2);
}
// sort based on a numeric or localeCompare, based on type...
//return (v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2))
// ? v1 - v2
// : v1.toString().localeCompare(v2);
return x;
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
NOTE: this will only work if the date you are trying to parse is a string in the dd-mm-YY format.
If you need a different format change the includes() and the split() character (in my case is "-") and the order of the date you are creating with Date().
If there's something wrong with this method please comment.