In the following jQuery code, the table column will get sorted after clicking on its header. The whole table will also get sorted according to the column.
The variable 'asc' will take care of sorting the column ascending or descending.
Note: If the column values are of number type, then those will be sorted after converting values to number.
Note: If the column values are of number type, then those will be sorted after converting values to number.
var asc = 1;
$('#bookSearch th').on('click',function() {
asc *= -1;
let tbody = $('tbody')[0], col = $(this).index();
let rows = tbody.rows, arr = [], cells;
// fill the array with values from the table
for (let i = 0; i < rows.length; i++) {
cells = rows[i].cells;
arr[i] = [];
for (let j = 0; j < cells.length; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
// sort the array by the specified column number (col) and order (asc)
arr.sort(function(a, b) {
if(!isNaN(a[col])) {
return (+(a[col]) == +(b[col])) ? 0 : ((+(a[col]) > +(b[col])) ? asc : -1 * asc);
} else {
return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc);
}
});
// replace existing rows with new rows created from the sorted array
for(i = 0; i < rows.length; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
});
Comments
Post a Comment
Please feel free to comment. I would love to hear feedback.