Created
October 31, 2014 14:01
-
-
Save bloodyburger/ad09c70cdf0e3c6e4a7c to your computer and use it in GitHub Desktop.
Move table rows across tables in JQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Table Source Code | |
<table id="table1" style="background-color: Lime" class="displayTable"> | |
<caption>Table 1</caption> | |
<thead> | |
<tr> | |
<th>One</th> | |
<th>Two</th> | |
<th>Three</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr id="row1"> | |
<td>R1 C1</td> | |
<td>R1 C2</td> | |
<td> | |
<a href="#" id="row1Link" class="rowLink">Move Me</a> | | |
<a href="#" id="row1Up" class="rowUp">Up</a> | | |
<a href="#" id="row1Down" class="rowDown">Down</a> | |
</td> | |
</tr> | |
<tr id="row2"> | |
<td>R2 C1</td> | |
<td>R2 C2</td> | |
<td> | |
<a href="#" id="row2Link" class="rowLink">Move Me</a> | | |
<a href="#" id="row2Up" class="rowUp">Up</a> | | |
<a href="#" id="row2Down" class="rowDown">Down</a> | |
</td> | |
</tr> | |
<tr id="row3"> | |
<td>R3 C1</td> | |
<td>R3 C2</td> | |
<td> | |
<a href="#" id="row3Link" class="rowLink">Move Me</a> | | |
<a href="#" id="row3Up" class="rowUp">Up</a> | | |
<a href="#" id="row3Down" class="rowDown">Down</a> | |
</td> | |
</tr> | |
</tbody> | |
</table> | |
<table id="table2" style="background-color: Yellow; margin-top: 30px;" class="displayTable"> | |
<caption>Table 2</caption> | |
<thead> | |
<tr> | |
<th>One</th> | |
<th>Two</th> | |
<th>Three</th> | |
</tr> | |
</thead> | |
<tbody> | |
</tbody> | |
</table> | |
JS to move between tables | |
// Setup the "Move Me" links | |
$(".rowLink").click(function () { | |
// get the row containing this link | |
var row = $(this).closest("tr").remove().clone(); | |
// find out in which table it resides | |
var table = $(this).closest("table"); | |
// move it | |
row.detach(); | |
if (table.is("#table1")) { | |
row.appendTo('#table2'); | |
} | |
else { | |
row.appendTo('#table1'); | |
} | |
// draw the user's attention to it | |
row.fadeOut(); | |
row.fadeIn(); | |
}); | |
JS to move Up and Down | |
// Setup the "Up" links | |
$(".rowUp").click(function () { | |
var row = $(this).closest("tr"); | |
// Get the previous element in the DOM | |
var previous = row.prev(); | |
// Check to see if it is a row | |
if (previous.is("tr")) { | |
// Move row above previous | |
row.detach(); | |
previous.before(row); | |
// draw the user's attention to it | |
row.fadeOut(); | |
row.fadeIn(); | |
} | |
// else - already at the top | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment