Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind events to dynamically added elements

Tags:

html

jquery

ajax

I'm trying to bind functions to newly added elements using jquery...I have tried numerous examples online, but somehow nothing works for me. I created a form with id and a button, on submit ajax loads elements from another page and inserts the html on current website. Everything seems to work fine, but the newly loaded elements don't have any events binded on. Here is the html:

<form id="tclick" method="post" action="${tg.url('/entryCmd')}">
    <input type="hidden" name="id" value="${entries[0].id}"  />
    <input type="submit" value="submit"/>
</form>

and jQuery:

$("#tclick").on("submit", function(data){
    var h = $(this).serialize();
    var d;

    $.get($(this).attr("action"), h, 
        function(returnData) {
            d = returnData;
        }
    );

    $(this).ajaxStop(function(){
        $(this).after($(d).find(".edit-content").html());
    });

    return false;
});

The edit-content div gets loaded right after the form element. It has some a elements, that sould be bound to jQuery functions.

like image 258
Alko Avatar asked Jan 10 '12 15:01

Alko


1 Answers

Got basically two options to do this:

  1. Bind your events after appending the new html:

    $(this).ajaxStop(function(){
         $(this).after($(d).find(".edit-content").html());
         // do you binding here
    });
    
  2. Use event delegation (with .on() or .delegate()).

    $('.some-container').on('click', '.edit-button', function(e) {...});
    

    This will delegate the click event to an element .some-container for any children with class .edit-button, not matter the latter was already in the dom or loaded afterwards.

like image 67
Didier Ghys Avatar answered Sep 29 '22 05:09

Didier Ghys