views:

39

answers:

2

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>
A: 

Have a look at how this plugin lets you to sort elements, though it adds a visual effect you can exclude it.

Alberto Zaccagni
+1  A: 
<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/

Kai
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
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
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
I have updated.Plz check http://www.jsfiddle.net/HELUq/8/
Kai
Thanks. Just what I needed.
Chris