Reputation: 771
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.
Upvotes: 5
Views: 3073
Reputation: 30666
Got basically two options to do this:
Bind your events after appending the new html:
$(this).ajaxStop(function(){
$(this).after($(d).find(".edit-content").html());
// do you binding here
});
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.
Upvotes: 4
Reputation: 337560
To add events to elements which are added to the DOM after page load you need to use either delegate()
, or if you're using jQuery 1.7+ on()
.
$(".edit-content").delegate("#myDiv", "click", function() {
// do stuff when #myDiv gets clicked.
});
Upvotes: 1