Amol
Amol

Reputation: 303

jQuery click event not working for dynamically added elements

I have been trying to use jQuery on this code but it is not responsive. I dynamically try to add some rows to the end of an HTML table and I have also included a cancel button. The click function on the cancel button doesn't seem to work.

I can't post full code here, so I included a link to the jsFiddle.

Part of JavaScript code:

$('#myTable tbody:last').after('<tbody class="newrow"><tr><td> <input  type="text" class="app"></td><td><input type="text" class="env"> |\n\
 </td><td><input type="text" class="region"> | </td><td><input type="text"  class="url"> | \n\
</td><td><button class="cancel">X</button></td>\n\
</tr></tbody>');          
}

$('.cancel').on('click', function() {
    alert();
   //$(this).closest('tbody').fadeOut(2000); 
});

Upvotes: 0

Views: 62

Answers (2)

Lajon
Lajon

Reputation: 321

Create unique class for each cancel obj

<button class="cancel' + counter + '">X</button>

and initiate the trigger then, full solution:

     var counter = 0;//specify counter variable to create unique cancel class
     $('.addfinal').click(function(){   
          n=$('.addno').val();
          for(var i=0;i<n;i++){

         $('#myTable tbody:last').after('<tbody class="newrow"><tr><td><input type="text" class="app"></td><td><input type="text" class="env"> |\n\                  </td><td><input type="text" class="region"> | </td><td><input type="text"      class="url"> | \n\</td><td><button class="cancel' + counter + '">X</button></td>\n\</tr></tbody>');
     } 


            cancel($(".cancel"+counter))
            counter++;
     });
});

When you initiate click event for cancel class then that class doesn't exists yet, try to wrap it in the function and attach this click event for each cancel obj that you will create with the row, your cancel objects will have a unique id now thanks to counter variable (see above).

function cancel($obj){
    $obj.on('click', function() {
         console.log($(this).closest('tbody'))
         $(this).closest('tbody').fadeOut(2000); 
    });
}

Upvotes: 0

Alex Andrei
Alex Andrei

Reputation: 7283

You need to use delegated events in order to catch click events for dinamycally added elements.

After you implement the changes proposed in the comments, change your click handler to this

$('body').on('click','.cancel', function() {
    console.log($(this));
    //$(this).closest('tbody').fadeOut(2000); 
});

This will output in the browser console, the button that has been clicked, it should work on the new elements also.

Upvotes: 3

Related Questions