in Web and Tech, Work

Sorting an HTML table using JQuery

function sortTable(table, order, nr) {
var asc = order === 'asc',
tbody = table.find('tbody');

tbody.find('tr').sort(function(a, b) {
if (asc) {
return $('td:nth-child('+ nr +')', a).text().localeCompare($('td:nth-child('+ nr +')', b).text());
} else {
return $('td:nth-child('+ nr +')', b).text().localeCompare($('td:nth-child('+ nr +')', a).text());
}
}).appendTo(tbody);
}

sortTable($('#mytable'),'asc', 1);

References:

Native Javascript solutions:
https://stackoverflow.com/questions/22906760/jquery-sort-table-data

JQuery solutions:
Echoed from: https://blog.niklasottosson.com/javascript/jquery-sort-table-rows-on-column-value/
http://jsfiddle.net/6sskjbod/1682/

Write a Comment

Comment