JQuery Move Table Rows Up And Down

To simply and easily move table rows up and down with in the table, use jquery.

With a table like:

<table>
<tbody>
<tr class="MoveableRow">
<td>Data 1</td>
<td><span class="down_button">down</span><span class="up_button">up</span></td>
</tr>
<tr></tr>
<tr class="MoveableRow">
<td>Data 2</td>
<td><span class="down_button">down</span><span class="up_button">up</span></td>
</tr>
<tr></tr>
</tbody>
</table>

You can then have some javascript like:


            $('.down_button').live('click', function () {
                var rowToMove = $(this).parents('tr.MoveableRow:first');
                var next = rowToMove.next('tr.MoveableRow')
                if (next.length == 1) { next.after(rowToMove); }
            });

            $('.up_button').live('click', function () {
                var rowToMove = $(this).parents('tr.MoveableRow:first');
                var prev = rowToMove.prev('tr.MoveableRow')
                if (prev.length == 1) { prev.before(rowToMove); }
            });

Previously I found a post somewhere that used the replaceWith method of jQuery. This wouldn’t retain newly written text in input boxes I had there. after and before work like charms, because you can pass in a jquery object as the content. Pretty slick.

Advertisements

6 thoughts on “JQuery Move Table Rows Up And Down

  1. I have a table extracted from mysql database. I want to move the rows up and down on front end, which will update the table in the database also. How to do it?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s