2

I have this code:

<table>
 <tr id="a"><td>A</td></tr>
 <tr id="d"><td>D</td></tr>
 <tr id="e"><td>E</td></tr>
 <tr id="b"><td>B</td></tr>
 <tr id="c"><td>C</td></tr>
</table>

How with jQuery can I put the rows in order?


Update: I need to use a move function not a sort function, since the real id's are not letters. Sorry for the confusion. I want to do something like this:

$("#a").after(rows_b_and_c)

But I don't know how to get the rows.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Memochipan
  • 3,405
  • 5
  • 35
  • 60

2 Answers2

2

if you have no events attached to <td>s and contents are just text, this will do:

var tds = $('table tr').sort(function(a,b){
    return $('td:eq(0)',a).text() > $('td:eq(0)',b).text();
});
$('table').html(tds);

jsfiddle demo


that depends... how would you order it? please be more specific.

will to give you a hint, you might wanna check out:

.after() Insert content, specified by the parameter, after each element in the set of matched elements.

.before() Insert content, specified by the parameter, before each element in the set of matched elements.

.insertAfter() Insert every element in the set of matched elements after the target.

.insertBefore() Insert every element in the set of matched elements before the target.


you're funny. :p

you said you know those functions then you did not get to solve the problem.

anyway, here are some of the ways to do it: http://jsfiddle.net/reigel/7Pb6a/1/

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • Smart solution @Reigel, but I used the letters only as example, the real ids are random text and the objective is to move the rows, no to sort them. – Memochipan Oct 14 '11 at 01:10
  • move rows when you click them? sorry if I misunderstood your question. – Reigel Gallarde Oct 14 '11 at 01:13
  • I receive the output of an inflexive php code that displays the rows in an incorrect order, I want to re-order them using jQuery. – Memochipan Oct 14 '11 at 01:18
  • I know those functions, but I don't know how to get the rows to put `$("#a").after(rows)` – Memochipan Oct 14 '11 at 01:53
  • Hahaha, You're right @Reigel, I was confused. English is not my language and I didn't understand the difference between after and insertAfter. Somewhere I read that .html() doesn't get the tags of the element, so I couldn't use it to pass data to .after(). Thanks for understand me and have patience! :) – Memochipan Oct 14 '11 at 12:00
1

Cleaner:

var sortID = function(a,b){
    return a.id > b.id ? 1 : -1;
};
$('table tr').sort(sortID).appendTo('table');
N Rohler
  • 4,595
  • 24
  • 20