tags:

views:

62

answers:

2

I have a table like this:

<table>
  <tr>  
    <td>something</td>
  </tr>
  <tr>
    <td>something else</td>
  </tr>
</table>

now based on an id that is in the td i want to move the tr's around so that they are in the position held by the id. any ideas on how to do this?

+1  A: 

Not good for ordering of large tables, but this worked for me when i wrote it a while back. You would be ordering on something different (the row id) so you will have to change it to suite your needs.

the first argument is the table you want to sort, the second is the column you would sort on.

you would change all the cIndex stuff to use your rowid instead.

function SortTable(stable, cIndex)
{
    var rows = $(stable).find("tr");
    var count = $(rows).size();

    for (var i = 0; i < count - 1; i++)
    {
        var r1 = $(rows[i]);
        var r2 = $(rows[i + 1]);

        var td1 = $(r1).find("td")[cIndex];
        var td2 = $(r2).find("td")[cIndex];

        var d1 = parseInt($(td1).html());
        var d2 = parseInt($(td2).html());

        if (d1 < d2)
        {
            var t = rows[i];
            rows[i] = rows[i + 1]
            rows[i + 1] = t;
            i = -1;
        }
    }

    var tbody = $(stable);
    tbody.empty();
    for (var i = 0; i < count; i++)
    {
        $(tbody).append(rows[i]);
    }
}
John Boker
+1  A: 

You can select the tr by using the parent() function. For example,

$("#td-id").parent().appendTo("table");

will move the tr containing the td with the id "td-id" to the bottom of the table.

emmychan