Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a <tr> up or down within <table> via jQuery?

Tags:

jquery

What's the elegant way to do this?

like image 821
user198729 Avatar asked Dec 17 '22 04:12

user198729


2 Answers

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

like image 79
Alex Sexton Avatar answered Dec 19 '22 19:12

Alex Sexton


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);
            }
        });
    }
});
like image 39
John McMillion Avatar answered Dec 19 '22 19:12

John McMillion