Question

So basically i'm appending two different thinds inside a table, with the same .parent().parent().remove() mehtod, in the first table it works, in the second it doesn't.

Any ideas?

Here is the code. http://jsfiddle.net/rzmA4/

 $(document).ready(function(){
      $('#adauga_model').on('click', function(){
           $('#modele_adaugate').append('<tr><td><input type="file" name="model[]"></td><td><button class="remove" type="button">Remove</button></td></tr>');
      });
      $('#adauga_design').on('click', function(){
           $('#designuri_adaugate').append('<tr><td><input type="file" name="design[]"></td><td><button class="remove" type="button">Remove2</button></td></tr>');
      });
      $("td").on('click', '.remove', function() {
           $(this).parent().parent().remove();
           return false;
      });
 });
Was it helpful?

Solution

It is interesting that it worked on the first one at all, but you are adding an event listener to all TD elements when the document loads. However, you are creating new ones, which do not have the event listener.

I rewrote the script as follows to solve the problem:

 $("body").on('click', 'td .remove', function() {
      $(this).closest("tr").remove();
      return false;
 });

As a bonus: Using closest("tr") is better than doing parent().parent(). When you do the latter and you later change your design, you might get a bug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top