How to move <tr> up or down in <table> via jQuery?
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
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
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
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