Walberg Walberg - 3 months ago 11
jQuery Question

jquery each function not getting executed on dynamically added elements

Why .each is not functioning on dynamically created buttons.

<div id="content"></div>
<button id="clickBut">Click</button>


js:

$("#clickBut").on("click", function(){
console.log("b clicked");
$("#content").append("<div class='buttnContent'><button class='db'>dyn but</button></div><div class='buttnContent'><button class='db'>dyn but</button></div>");
});

$("#content").find(".db").each(function(i,v){
$(this).on("click",function(){
console.log("dyn but: "+i);
});
});


when I am clicking on dynamic buttons, nothing is happening.But if i remove each function and clicking then click function is getting executed.
i want value of i to be displayed.Please share your inputs

Answer

You need to use event delegation for listen to the click event of dynamically added element. Inside handler use index() method to get the index of the button.

$("#content").on("click",'.db',function(){
  console.log("dyn but: " + $("#content .db").index(this)); 
})

$("#clickBut").on("click", function() {
  console.log("b clicked");
  $("#content").append("<div class='buttnContent'><button class='db'>dyn but</button></div><div class='buttnContent'><button class='db'>dyn but</button></div>");
});

$("#content").on("click", '.db', function() {
  console.log("dyn but: " + $("#content .db").index(this));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button id="clickBut">Click</button>
js: