Maroof Maroof - 3 months ago 11
HTML Question

Adding event Listener to Dynamically Added HTML Elements

I have the HTML

<input type="button" class="btnx" value="click me">


and the attached JS file

$(".btnx").on("click",function(){
var newbtn = "<input type='button' class='btnx' value='click me'>";
$('body').append(newbtn);
});


When I click on the button 1 new buttons are append to the body, but when I click on the new buttons(button 2 or button 3) why no more buttons are formed.

I googled and found to use ".on()" but still can't figure out why it is not working.

JSFiddle link:
https://jsfiddle.net/93k9emL1/

Answer

You can use $('body').on('click', '.btnx', ...) for that:

$("body").on("click", '.btnx', function(){
	var newbtn = "<input type='button' class='btnx' value='click me'>";
  $('body').append($(newbtn));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btnx" value="click me">

Explanation regarding your code:

The problem with your code was that the new element that you added to the DOM tree didn't have the click event attached to it.
The way to make this work is to attache the click event to the body element, and use the .btnx selector. This way the code will work with every click you have, also for new elements that you add.

Comments