So I have a HTML table inside my PHP page (filled from MySQL database) and a specific column that I want to sort it numerically on click on the column header. Alphabetically, the sort function is working with no problem. Numerically, the sort function works only when I put data with no hyperlinks. Here are the table (with and without hyperlink):
<table id="myTable">
<thead >
<tr style="cursor: pointer;">
<th onclick="sortTableId()">ID</th>
<th onclick="sortTable(1)">Titre</th>
<th onclick="sortTable(2)">Date de création</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<table id="myTable">
<thead >
<tr style="cursor: pointer;">
<th onclick="sortTableId()">ID</th>
<th onclick="sortTable(1)">Titre</th>
<th onclick="sortTable(2)">Date de création</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><a href=petition-admin.php?id=<?php echo $row[0]?>'><?php echo $row[0]; ?></a></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
And the JavaScript sort function :
function sortTableId() {
var table, rows, switching, i, x, y, a, b, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i ) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i 1].getElementsByTagName("TD")[0];
if (dir == "asc") {
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
else if (dir == "desc") {
if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i 1], rows[i]);
switching = true;
switchcount ;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
} A screenshot of the table : Table
CodePudding user response:
You are using innerHTML
which will include the inner HTML markup so numeric conversion will be ... interesting.
Use innerText
or textContent
instead.
Eg:
if (Number(x.innerText) > Number(y.innerText))
If you wanted to get really fancy you could add a data-sortdata
data attribute and perhaps a data-sortdatatype
attribute to handle things like currency ($4,000.00) boolean or images in cells (think check marks for bools etc) and perform your sort on these instead of markup in cells