Matt Becker
Matt Becker

Reputation: 13

Move table row from one table to another using JQuery

I am attempting to move a row from one table into another and back again.

I have this working going to the first table but the going back event is not firing. Here is my code

html

<table id="table_source">
    <tbody>
        <tr>
            <td>Row</td>
            <td>1</td>
            <td><img src='move_image_path' alt='Move' class='move-row' /></td>
        </tr>
        <tr>
            <td>Another Row</td>
            <td>2</td>
            <td><img src='move_image_path' alt='Move' class='move-row' /></td>
        </tr>
    </tbody>
</table>
   <table id="table_dest" class="active"><a href="#">People</a>
        <tbody>
          <tr>
          </tr>  
        </tbody>
    </table>

Jquery

  $("#table_source img.move-row").click(function (e) {            
             var tr = $(this).closest("tr").remove().clone();
             tr.find("img.move-row")
        .attr("src", "remove_image_path.jpg")
        .attr("alt", "Remove");
             $("#table_dest tbody").append(tr);
         });

         $("#table_dest img.move-row").click(function (e) {
             alert("hi") //THIS IS NOT FIRING
             var tr = $(this).closest("tr").remove().clone();
             tr.find("img.move-row")
        .attr("src", "move_image_path.jpg")
        .attr("alt", "Move");
             $("#table_source tbody").append(tr);
         });

Upvotes: 0

Views: 2471

Answers (1)

Andr&#233; Silva
Andr&#233; Silva

Reputation: 1108

You have to use the on jQuery callback.

 $("#table_dest").on('click', 'img.move-row', function (e) {
     alert("hi") //THIS IS NOT FIRING
     var tr = $(this).closest("tr").remove().clone();
     tr.find("img.move-row")
         .attr("src", "move_image_path.jpg")
         .attr("alt", "Move");
     $("#table_source tbody").append(tr);
 });

Initially, when the page loads the click events are binded to the existing images. The ones that are added dinamically don't have the event attached to them. By using the on(), you stop having this issue.

Upvotes: 1

Related Questions