What's the elegant way to do this?
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'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);
}
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With