I have 3 columns:
column1 | Column2 | Column3 |
---|---|---|
111111 | 111111 | 1 |
444444 | 444444 | 4 |
333333 | 333333 | 3 |
222222 | 222222 | two |
555555 | 555555 | 5 |
666666 | 666666 | 6 |
If I click on Columna1
, Columna2
or Columna3
the table is sorted from smallest to largest :
Column1 | Column2 | Column3 |
---|---|---|
111111 | 111111 | 1 |
222222 | 222222 | two |
333333 | 333333 | 3 |
444444 | 444444 | 4 |
555555 | 555555 | 5 |
666666 | 666666 | 6 |
But if I click again I am not sorted from highest to lowest, what am I doing wrong?
$(document).ready(() => {
$('th').each(function (columna) {
$(this).click(function () {
console.log("clickeado columna");
let registros = $('table').find('tbody > tr').get();
registros.sort(function (a, b) {
console.log("sort");
let valor1 = parseInt($(a).children('td').eq(columna).text().toUpperCase(), 16);
let valor2 = parseInt($(b).children('td').eq(columna).text().toUpperCase(), 16);
return valor1 < valor2 ? -1 : valor1 > valor2 ? 1 : 0
});
$.each(registros, function (indice, elemento) {
$('tbody').append(elemento);
});
});
});
});
Use two console.log
to know if it reached the function and if it entered sort()
.
The first time I click on the column, it appears:
"clickeado columna"
(672) sort
And from the second time onwards:
"clickeado columna"
(121) sort
There are currently 122 records in the table
$(document).ready(() => {
$('th').each(function (columna) {
$(this).click(function () {
let registros = $('table').find('tbody > tr').get();
registros.sort(function (a, b) {
let valor1 = parseInt($(a).children('td').eq(columna).text().toUpperCase(), 16);
let valor2 = parseInt($(b).children('td').eq(columna).text().toUpperCase(), 16);
return valor1 < valor2 ? -1 : valor1 > valor2 ? 1 : 0
});
$.each(registros, function (indice, elemento) {
$('tbody').append(elemento);
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<table>
<thead>
<tr>
<th>Columna 1</th>
<th>Columna 2</th>
<th>Columna 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>11111</td>
<td>11111</td>
<td>1</td>
</tr>
<tr>
<td>33333</td>
<td>33333</td>
<td>3</td>
</tr>
<tr>
<td>22222</td>
<td>22222</td>
<td>2</td>
</tr>
<tr>
<td>44444</td>
<td>44444</td>
<td>4</td>
</tr>
<tr>
<td>66666</td>
<td>66666</td>
<td>6</td>
</tr>
<tr>
<td>55555</td>
<td>55555</td>
<td>5</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>