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

What an elegant way to do this?

+4
source share
6 answers

Here is a quick plugin that I wrote for you. Name it on the table and give it 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 is a jsbin example: http://jsbin.com/uroyi

+6
source

Alex's answer works fine, but found one problem, if you move something to the very end of the list, it cannot insert it. Here's a slightly modified 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); } }); } }); 
+4
source

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)); } 
+1
source

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(); 
0
source

If you want to move it to the top or bottom, it will be easier, although it will not help you :(

 //lets say you want to avoid/skip table headers and use a tbody var tbody = $('tbody','#table'); //now you want a specific row bring to top $('tr.chieftan',tbody).prependTo(tbody); 

To go from a specific index to a specific:

 $('li:eq(2)').insertBefore($('li:eq(1)')); 

Move the third child to the second (indexes based on 0).

0
source

I would assign identifiers to all my <tr> s.

-one
source

All Articles