Erdinç Özdemir
Erdinç Özdemir

Reputation: 1381

Move <tr> with JQuery

I have a table on my page like this:

 <table border="1">
    <tr>
        <td>first</td>
        <td><a href="#">first click</a></td>
     </tr>
     <tr>
         <td>second</td>
         <td><a href="#">second click</a></td>
     </tr>
     <tr>
         <td>third</td>
         <td><a href="#">third click</a></td>
     </tr>
     <tr id="change">
         <td colspan="2">
            <button>change</button>
          </td>
     </tr>
  </table>

When I click on of the links, I want the move '#change' under the clicked link's . For example; when I click on "first click" table changes like this..

 <table border="1">
    <tr>
        <td>first</td>
        <td><a href="#">first click</a></td>
     </tr>
     <tr id="change">
         <td colspan="2">
            <button>change</button>
          </td>
     </tr>
     <tr>
         <td>second</td>
         <td><a href="#">second click</a></td>
     </tr>
     <tr>
         <td>third</td>
         <td><a href="#">third click</a></td>
     </tr>
  </table>

How can I do it with JQuery?

Upvotes: 3

Views: 756

Answers (5)

Sampson
Sampson

Reputation: 268414

Using event delegation, therefore only adding on event listener to the mix rather than several:

// Using Event Delegation only adds one event listener
​$("table").on("click", "a", function (event) {
    // Prevent any navigation or jumping to the top of the page
    event.preventDefault();
    // Find the closest <tr>, insert #change after it.
    $(this).closest("tr").after($("#change"));
});​​​​​​​​

Upvotes: 1

SimaWB
SimaWB

Reputation: 9294

$("a").click( function(){
  var $change = $('#change');
  $('#change').remove();  
  $(this).closest('tr').after($change);
});​

Upvotes: 0

Ian Overton
Ian Overton

Reputation: 1060

jQuery('td a').click(function(){
    $(this).parents("tr").after($('#change'));
});

http://jsfiddle.net/6AMnV/

Upvotes: 1

gpojd
gpojd

Reputation: 23075

Try this:

$('table tr td a').click(function () {
    $(this).closest('tr').after($('#change'));
});​

fiddle

Upvotes: 2

silly
silly

Reputation: 7887

try this (untested)

jQuery('td a').each(function(){
    var j = jQuery(this);
    jTr = j.closest('table').find('#change');
    j.closest('tr').after(jTr);
});

Upvotes: 0

Related Questions