1

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/

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah It is working but what is the problem in my code ? I cant understand.
Added explanation in the answer, let me know if it was clear enough :)
Thanks, now i get it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.