I’m trying to write a JavaScript / jQuery function that is called when a button with the class "add-row" is clicked. The function appends HTML to the DOM that adds another button with the same class. What I want is that when that second button is clicked, the function will be called again and create yet another button, and so on.
Here’s the code for the first button:
<div>
<label for="add_row-0"></label><br>
<button type="button" class="add-row">Add Another Item</button>
</div>
And here’s the JavaScript function:
$(document).ready(function(){
$(".add-row").click(function(){
$(".add-row").last().after(
`<div>
<label for=${button_identifier}></label><br>
<button type="button" class="add-row">Add Another Item</button>
</div>
</div>`
);
});
});
This isn’t working – what’s happening is that the first button works fine and calls the function that creates the second button, but clicking on the second button does nothing.
2
Answers
Use event delegation on the nearest static ancestor of all the
<div>
containers with the buttons.document
is used here as an example, but you should replace it with the nearest static ancestor for better performance.In your there are 2 things to tell,
1- the .click() function doesn’t work on newely appended(injected) elements on the dom, it works only on the rendered elemnts with page load.
2- in order to get your click function to work on newely appended elements, you need to use .on("click") function, so you listen on the document for click. =>
so your code should be like