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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With