What's the elegant way to do this?
A:
Maybe this link would help you a bit: http://stackoverflow.com/questions/444801/move-x-number-of-rows-in-a-table-using-jquery
Regards, Paul
Paul Peelen
2009-12-04 08:26:08
A:
HTML:
<table id="t1">
<tr>
<td>abc</td>
</tr>
<tr>
<td>efg</td>
</tr>
</table>
Javascript (jQuery):
var row0 = $('#t1 tr:eq(0)');
$('#t1 tr:eq(1)').after(row0.contents());
row0.remove();
micahwittman
2009-12-04 08:32:54
+4
A:
Here's a quick plugin I wrote for you. Call it on a table, and give it the the old row and the new row position.
$.fn.extend({
moveRow: function(oldPosition, newPosition) {
return this.each(function(){
var row = $(this).find('tr').eq(oldPosition).remove();
$(this).find('tr').eq(newPosition).before(row);
});
}
});
$('#myTable').moveRow(4, 3);
Here's an example on jsbin: http://jsbin.com/uroyi
Alex Sexton
2009-12-04 08:44:05
+1 - very succinct answer. If the `<tr>` has event handlers bound to it, will this plugin preserve them?
Russ Cam
2009-12-04 08:57:45
Sorry but it won't. According to the jQuery documentation you will need to do an appendTo directly to preserve the event handlers.http://docs.jquery.com/Manipulation/remove#expr
bang
2009-12-04 09:18:46
I removed my comment above since i was wrong, here's the info I still stand by. Thanks bang, for calling me out.The events will not be saved. I would suggest using $.live() as it would be more efficient for any more than 3+ rows. In the case of live, the events aren't attached directly to the element anyways, so it would work with less-friendly plugin.
Alex Sexton
2009-12-04 09:21:11
you could also `clone(true)` the row before removing it and then insert the clone.
Russ Cam
2009-12-04 09:44:33
A note for jQuery 1.4.x+ - instead of the `remove` you can use a `detach` and it will keep the events.
Alex Sexton
2010-03-19 04:13:02
+1
A:
Here are two javascript functions that will do the job:
function MoveRowDown(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertAfter(rows.eq(index + 1));
}
function MoveRowUp(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertBefore(rows.eq(index - 1));
}
bang
2009-12-04 08:45:15
A:
Alex's answer works great, but found one issue, if you move something to the very end of the list, it can't insert it. Here's a slightly tweaked version that fixes it...
$.fn.extend({
moveRow: function (oldPosition, newPosition) {
return this.each(function () {
var row = $(this).find('tr').eq(oldPosition).detach();
if (newPosition == $(this).find('tr').length) {
$(this).find('tr').eq(newPosition - 1).after(row);
}
else {
$(this).find('tr').eq(newPosition).before(row);
}
});
}
});