Skip to content Skip to sidebar Skip to footer

Jquery Event Not Triggering On Dynamically Created Element

Here goes my question.. /* I am using ajax to dynamically create table */ $('.n').click(function(){ var id= $(this).closest('tr').find('td.ide2').html();

Solution 1:

Ajax calls are asynchronous.

Before the elements are appended via ajax, the click handler gets registered, which find no elements with $(".off-del").

You should probably use event delegation.

$(document).on('click','.off-del',function(){
    alert('hello');
    var id= $(this).closest('tr').find($(":first-child")).html();
    console.log(id);
});

Instead of $(document) you can use a static parent.

Solution 2:

When you set up an event handler in jQuery like this:

      $(".off-del").click(function(){
        alert('hello');
        var id= $(this).closest('tr').find($(":first-child")).html();
        console.log(id);
      });

you're telling it to go find the elements with class "off-del" in the document right at that moment. Your ajax operations will add such elements, but it'll only happen after your attempt to set up the handlers.

Instead of that, you can set up the handler on the document object and take advantage of event bubbling:

$(document).on("click", ".off-del", function() {
      alert('hello');
      var id= $(this).closest('tr').find($(":first-child")).html();
      console.log(id);
});

You can set up the event handler that way any time you want, and it'll handle clicks from any ".off-del" element added at any time.

Solution 3:

You are facing this issue because after your dynamically created html you are also supposed to load that event which will bind it to newly created html.

So create a function for event and make a call to that function after dynamically created html.

Solution 4:

While you can use event delegation for this - you could also just register the handler after you've appended all the HTML (inside the success callback)

for(var i=0;i<(resp.length);i++) {
    var row = $('<tr></tr>').appendTo($("#unique-list"));
    $('<td />',{text:resp[i]}).appendTo(row);
    $('<td class="off-del glyphicon glyphicon-minus"></td>').appendTo(row);  
}//end for loop

$(".off-del").click(function(){
      alert('hello');
      var id= $(this).closest('tr').find($(":first-child")).html();
      console.log(id);
});

Post a Comment for "Jquery Event Not Triggering On Dynamically Created Element"