brg brg - 4 months ago 4
Javascript Question

how to make click event work with dynamically generated html elements

When the add more link is clicked, a div is dynamically generated that adds an additional text input and a add more link. This dynamically inserted add more link doesn't respond to click event. Even though each dynamically inserted link has a unique id and the click event uses "delegated" binding through Jquery on() method, yet the dynamically inserted link does not work by adding more fields when clicked. Here is a jsbin and the whole code is below:

The javascript:

<script type="text/javascript">
$(document).on("ready", function(){

return $(".add_people_filter").on("click", function(event){

event.preventDefault();

var time = new Date().getTime();
var dynamicallyCreatedDiv = document.createElement("div");
dynamicallyCreatedDiv.id = time;

var peopleFilterContainerDiv = $("#people_filter_container");
peopleFilterContainerDiv.append(dynamicallyCreatedDiv);
var getHtmlForDynamicDiv = $(".people_filter").html();
var theNewDiv = $(dynamicallyCreatedDiv);
theNewDiv.append(getHtmlForDynamicDiv);

var AddUniqueIdToLinK = time * 2;
var x = time * 3;
$(this).attr('id', AddUniqueIdToLinK);
theNewDiv.find("a:last").attr('id', x);

return theNewDiv;
});
});
</script>


The html:

<div id="people_filter_container">
<div class="people_filter" >
<input type="text" name="firstname" placeholder="add name" >
<a href="#" data-behavior="add_people_filter" class="add_people_filter"> add more</a>
<br> <br>
</div>

</div>

Leo Leo
Answer

Change it for that :

return $("body").on("click",".add_people_filter", function(event)
{
        ...... YOUR CODE      
});
Comments