Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move table row in jQuery?

Say I had links with up/down arrows for moving a table row up or down in order. What would be the most straightforward way to move that row up or down one position (using jQuery)?

There doesn't seem to be any direct way to do this using jQuery's built in methods, and after selecting the row with jQuery, I haven't found a way to then move it. Also, in my case, making the rows draggable (which I have done with a plugin previously) isn't an option.

like image 373
Wilco Avatar asked Oct 15 '09 01:10

Wilco


1 Answers

You could also do something pretty simple with the adjustable up/down..

given your links have a class of up or down you can wire this up in the click handler of the links. This is also under the assumption that the links are within each row of the grid.

$(document).ready(function(){     $(".up,.down").click(function(){         var row = $(this).parents("tr:first");         if ($(this).is(".up")) {             row.insertBefore(row.prev());         } else {             row.insertAfter(row.next());         }     }); }); 

HTML:

<table>     <tr>         <td>One</td>         <td>             <a href="#" class="up">Up</a>             <a href="#" class="down">Down</a>         </td>     </tr>     <tr>         <td>Two</td>         <td>             <a href="#" class="up">Up</a>             <a href="#" class="down">Down</a>         </td>     </tr>     <tr>         <td>Three</td>         <td>             <a href="#" class="up">Up</a>             <a href="#" class="down">Down</a>         </td>     </tr>     <tr>         <td>Four</td>         <td>             <a href="#" class="up">Up</a>             <a href="#" class="down">Down</a>         </td>     </tr>     <tr>         <td>Five</td>         <td>             <a href="#" class="up">Up</a>             <a href="#" class="down">Down</a>         </td>     </tr> </table> 

Demo - JsFiddle

like image 152
Quintin Robinson Avatar answered Sep 29 '22 18:09

Quintin Robinson