I have a basic HTML table setup that looks like this:
<table id="myTable">
<thead>
<tr>
<th class="pointer" onClick="sortTable()">Number</th>
<th>Example3</th>
<th>Example2</th>
<th>Example1</th>
</tr>
</thead>
<tbody>
<tr>
<td>101</td>
<td>TOM</td>
<td>Not Working</td>
<td>AUTOMAT-01</td>
</tr>
<tr>
<td>102</td>
<td>TOM</td>
<td>Not Working</td>
<td>AUTOMAT-02</td>
</tr>
</tbody>
</table>
The function for sorting the table in javascript is currently not functioning as expected. I am looking to sort the table in descending order based on the "Number" column. Additionally, I would like to include an arrow next to each column name that allows users to call the sorting function by clicking on the arrow.
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
/*Create a loop that continues until
no switching has been done:*/
while (switching) {
//start with no switches:
switching = false;
rows = table.rows;
/*Loop through all table rows (excluding the
header row):*/
for (i = 1; i < (rows.length - 1); i++) {
//assume no need to switch initially:
shouldSwitch = false;
/*Retrieve the elements to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i + 3].getElementsByTagName("TD")[0];
//check if the rows need to be switched:
if (Number(x.innerHTML) > Number(y.innerHTML)) {
//mark as needing a switch and break out of loop:
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If a switch is needed, then make the switch
and mark that a switch has occurred:*/
rows[i].parentNode.insertBefore(rows[i + 3], rows[i]);
switching = true;
}
}
}