Diasline
Diasline

Reputation: 635

Copy table row to another table row jquery

I see many others questions that seem like mine, but none of them corresponding to my need. Behold my 3 goals :

  1. If I click on checkbox row of tableFirst remove this row and copy it to tableSecond row
  2. Remove and Return ** this row of **tableSecond to tableFirst after clicking on checkbox of tableSecond row
  3. Once the row is return to tableFirst I should be able to return it to tableSecond again after clicking on his checkbox, this action should be vise versa

I successfully realize goal 1 and goal 2

  1. Goal 1

    jQuery('.copy-one').on('click', function(e) {
    if($(this).is(':checked',true)) {
    $(this).closest('tr').fadeOut(800, function(){ 
    $(this).remove();
    });
    $(this).closest('tr').clone().appendTo('#tableSecond>tbody');
    }
    
    })
    
  2. Goal 2

    $('#tableSecond').on('click','.copy-one',function(e){
     e.preventDefault();
    $(this).closest('tr').fadeOut(800, function(){ 
    $(this).remove();
    });
    $(this).closest('tr').clone().appendTo('#tableFirst>tbody');
    })
    
  3. I am stuck at goal 3.

Please help realize goal 3, my fiddle : http://jsfiddle.net/8ayrs3ed/5/

Upvotes: 1

Views: 51

Answers (1)

Snowmonkey
Snowmonkey

Reputation: 3761

So I notice, in #tableSecond, you're using event delegation. As you should, given that the event you're listening to is attached to a non-existent (at start) DOM node. The issue you're having is that you remove that DOM node from the first table, stick it in the second, and the second one's event handler, being delegated, catches it.

But in the first table, you are listening to the events at the class level. Instead, listen at #tableFirst.

jQuery('#tableFirst').on('click', ".copy-one", function(e) {
  if($(this).is(':checked',true)) {
    $(this).closest('tr').fadeOut(800, function(){ 
      $(this).remove();
    });
     $(this).closest('tr').clone().appendTo('#tableSecond>tbody');
  }
})

Event delegation is a perpetual gotcha. When you remove that DOM node form the first table, it is no longer handling its events. Thus you should listen at the container, and simply have IT manage inner events for dynamic elements.

To see it in action: your updated JSFiddle

Upvotes: 1

Related Questions