Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping rows in JQuery

Tags:

jquery

Here's another solution.

To move a row down:

jQuery("#rowid").next().after(jQuery("#rowid"));

To move a row up:

jQuery("#rowid").prev().before(jQuery("#rowid"));

$("#Row1").after($("#Row2"));

will work


Here's a slightly expanded example, hoping you will find it useful... :)

$('table').on('click', '.move-up', function () {
    var thisRow = $(this).closest('tr');
    var prevRow = thisRow.prev();
    if (prevRow.length) {
        prevRow.before(thisRow);
    }
});

$('table').on('click', '.move-down', function () {
    var thisRow = $(this).closest('tr');
    var nextRow = thisRow.next();
    if (nextRow.length) {
        nextRow.after(thisRow);
    }
});

Here's a plugin that does drag and drop table rows


To move Row1 one step down, you'd do:

$me = $("#Row1");
$me.after($me.nextSibling());

Here is the code to swap the rows. Lets take #Row1 and #Row3

$('#Row1').replaceWith($('#Row3').after($('#Row1').clone(true)));

The clone(true) is used so that events are also taken into account.

If you want to move row up and down then use this code. To move row UP

var tableRow = $("#Row1");
tableRow.insertBefore(tableRow.prev());

To move row DOWN

var tableRow = $("#Row1");
tableRow.insertAfter(tableRow.next());

I would try:

var tmp = $ ('#Row1')
$ ('#Row1').remove
$ ('#Row2').after ($ ('#Row1'))

But I guess it’s better to swap rows’ contents instead of swapping rows themselves, so that you can rely on numbering. Thus,

var tmp = $ ('#Row1').html ()
$ ('#Row1').html ($ ('#Row2').html ())
$ ('#Row2').html (tmp)