brg brg - 1 year ago 64
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){


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

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

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

return theNewDiv;

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>


Leo Leo
Answer Source

Change it for that :

return $("body").on("click",".add_people_filter", function(event)
        ...... YOUR CODE      
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download