In this chapter, we will learn how to use JS/CSS to implementtable sortingfunctionality.
First, let's look at the effect below. Click the button to sort (sort alphabetically in ascending order, based on the Name field):
Sorting Code
Example
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
/*Set up a loop statement*/
while (switching) {
//Set the loop end flag
switching = false;
rows = table.rows;
/*Loop through the table rows*/
for (i = 1; i < (rows.length - 1); i++) {
//Set whether elements should swap positions
shouldSwitch = false;
/*Get the elements to compare*/
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i + 1].getElementsByTagName("TD")[0];
//Determine whether to switch the next element with the current element
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//Set the swap flag and end the current loop
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If the element swap position is set to true, perform the swap operation*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
Try it Yourself »
Sort by Clicking Table Headers
Click the table header field to sort the table.
On the first click, the sort direction is ascending (A to Z).
Click again, the sort direction is descending (Z to A).
Example
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable2");
switching = true;
//Set ascending order
dir = "asc";
/*Set up a loop statement*/
while (switching) {
//Set the loop end flag
switching = false;
rows = table.rows;
/*Loop through the list, starting from the second row*/
for (i = 1; i < (rows.length - 1); i++) {
//Set whether elements should swap positions
shouldSwitch = false;
/*Get the elements to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*Determine whether to switch the next element with the current element (asc or desc):*/
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//Set the swap flag and end the current loop
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//Set the swap flag and end the current loop
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
/*If the element swap position is set to true, perform the swap operation*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a swap is completed, increase switchcount by 1
switchcount ++;
} else {
/*If all elements are sorted and direction is set to "asc", then set direction to "desc" and run the loop again*/
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
Try it Yourself »
Numeric Sorting
Example
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
Try it Yourself »