Sparafusile
Sparafusile

Reputation: 4956

How to swap two sets of rows in a table

I have two sets of rows in a table selected:

var slice1 = $( table ).children( "tr" ).slice( i - rowsPerItem, i );
var slice2 = $( table ).children( "tr" ).slice( i, i + rowsPerItem );

Which I can highlight using css and verify are the correct rows. Now I want to swap their position in the parent table as a set. They two sets are always one after the other in the table and contain the same number of rows.

Everything I've tried only moves one row:

$( slice1 ).after( slice2[slice2.length-1] );

How do I keep the sets or rows together, in the same order, but swap their position in the table?

Here's an example of what I'm seeing: http://jsfiddle.net/5vBfA/

Upvotes: 1

Views: 2176

Answers (2)

Ram
Ram

Reputation: 144689

Try using insertAfter method:

$("#SwapButton").click(function () {
    var i = 2;
    var rowsPerItem = 2;
    var $tr = $("#TheTable").find('tr');

    var $slice1 = $tr.slice(i - rowsPerItem, i);
    var $slice2 = $tr.slice(i, i + rowsPerItem);

    $slice1.insertAfter($slice2[$slice2.length - 1]);
});

http://jsfiddle.net/P2vSK/1/

Upvotes: 1

Zeal
Zeal

Reputation: 249

Have you tried this?

$(".anyOtherTableRow").after(slice1).after(slice2);

Upvotes: 0

Related Questions