Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sort table row by the value of one td

Tags:

jquery

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/

like image 619
user4571629 Avatar asked Mar 20 '15 13:03

user4571629


2 Answers

For having a valid table, you should wrap the first tr with a thead element and other trs with a tbody element. For sorting the trs 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 + '.';
});
like image 95
undefined Avatar answered Oct 10 '22 16:10

undefined


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');
    });
});
like image 44
Raidri Avatar answered Oct 10 '22 15:10

Raidri