13

I have a table with rows similar to the following. These rows get updated from time to time via jquery calls. Using jquery, how would I construct a function that reorders these table rows based on the myAttribute value putting the highest myAttribute value rows at the top and the lowest myAttribute value rows at the bottom? There could be up to 100 rows in the table.

<tr id='1' class='playerRow' myAttribute=5>
      <td> One</td>
      <td> Two</td>
</tr>
<tr id='2' class='playerRow' myAttribute=6>
      <td> One</td>
      <td> Two</td>
</tr>

2 Answers 2

28
<table>  
<tr id='1' class='playerRow' myAttribute='1'>
      <td> One1</td>
      <td> Two1</td>
</tr>
<tr id='2' class='playerRow' myAttribute='2'>
      <td> One2</td>
      <td> Two2</td>
</tr>
</table>

JQuery

var $table=$('table');

var rows = $table.find('tr').get();
rows.sort(function(a, b) {
var keyA = $(a).attr('myAttribute');
var keyB = $(b).attr('myAttribute');
if (keyA < keyB) return 1;
if (keyA > keyB) return -1;
return 0;
});
$.each(rows, function(index, row) {
$table.children('tbody').append(row);
});

Working Demo is http://www.jsfiddle.net/HELUq/1/

3
  • Thanks. jsfiddle is great. This is the first time that I have seen it. By the way, how would you alter this sort funciton if the myAttribute value was in one of the TD's? <td id='1' myAttribute='1'>
    – Chris
    Commented Jul 3, 2010 at 4:58
  • do u want to sort the TR using one of its TD's attribute or Do u want to sort the TD using its attribute? If your anwser is the first one, where exactly is TD located in its TR??(The first index,or etc..)
    – Kai
    Commented Jul 5, 2010 at 2:08
  • I want to sort the TR using one of its TD attributes. I can pass myAttribute in any of the TD values. I can put it in the first TD or whatever is simplest.
    – Chris
    Commented Jul 5, 2010 at 3:34
14

Thanks, Kai. I have distilled the code a little while preserving clarity. Generally, you don't want to sort the thead or tfooter parts. So, it may be handy to just target only the <tr> elements in the tbody (although this was not in Chris' original question):

    var tb = $('tbody');
    var rows = tb.find('tr');
    rows.sort(function(a, b) {
        var keyA = $(a).attr('myAttribute');
        var keyB = $(b).attr('myAttribute');
        return keyA - keyB;
    });
    $.each(rows, function(index, row) {
        tb.append(row);
    });

To sort in descending order, just reverse the return line as follows:

        return keyB - keyA;

Not the answer you're looking for? Browse other questions tagged or ask your own question.