How would you sort this table by the pts
class that I have:
<table>
<tr>
<th>rank</th>
<th>team</th>
<th>pts</th>
</tr>
<tr>
<td>1.</td>
<td>Chelsea</td>
<td class="pts">3</td>
</tr>
<tr>
<td>2.</td>
<td>Arsenal</td>
<td class="pts">1</td>
</tr>
<tr>
<td>3.</td>
<td>Man U</td>
<td class="pts">2</td>
</tr>
</table>
<button>SORT</button>
code: http://jsfiddle.net/dxL8b2k0/
For having a valid table, you should wrap the first tr
with a thead
element and other tr
s with a tbody
element. For sorting the tr
s you can use the sort
method:
$('tbody > tr').sort(function (a, b) {
return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody');
For updating the rank cells you can use the text
method:
$('tbody > tr').sort(function (a, b) {
return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody').find('td:first').text(function(index) {
return ++index + '.';
});
See this updated fiddle for a working version:
$('#btnGo').on('click', function () {
// get rows as array and detach them from the table
var rows = $('#tbl tr:not(:first)').detach();
// sort rows by the number in the td with class "pts"
rows.sort(function (row1, row2) {
return parseInt($(row1).find('td.pts').text()) - parseInt($(row2).find('td.pts').text());
});
// add each row back to the table in the sorted order (and update the rank)
var rank = 1;
rows.each(function () {
$(this).find('td:first').text(rank + '.');
rank++;
$(this).appendTo('#tbl');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With