Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: change the order of two rows of a table

Tags:

jquery

I want to change the order of two rows in a table.

I have this code:

console.log(position.parent().parent().prev());
console.log(position.parent().parent());
//I expected this line do the work, but no...
$(this).parent().parent().prev().insertAfter($(this).parent().parent());

That is printing this:

<tr>​
<td>​Element 1​</td>​
<td>​…​</td>​
<td>​2008-02-02​</td>​
<td class=​"jander" data-pos=​"0" data-category=​"1">​…​</td>​
</tr>​

<tr>​
<td>​Element 2​</td>​
<td>​…​</td>​
<td>​2007-02-02​</td>​
<td class=​"jander" data-pos=​"1" data-category=​"1">​…​</td>​
</tr>​

Any idea?

Regards

Javi

like image 799
ziiweb Avatar asked Jul 15 '11 20:07

ziiweb


1 Answers

var row = $(this).closest('tr');

row.insertAfter( row.next() );

Example: http://jsfiddle.net/hkkKs/

Depends on which one you're targeting. If the first one has the click handler, then you'd need the code above.

Also, the closest()[docs] method is a safer way to target the ancestor <tr>. That may have been the issue.

If you want it the opposite way, your code would work, but again, use .closest() instead.

$('span').click(function() {
    var row = $(this).closest('tr');

    row.prev().insertAfter(row);
});

Example: http://jsfiddle.net/hkkKs/1/

like image 100
user113716 Avatar answered Sep 24 '22 14:09

user113716