Skip to content
Advertisement

Clone and change onclick code of inner button

I have a div with id=”add-dependent” including 2 rows and a button (add dependent) inside of the div. When “add dependent” button is clicked, the first row would be cloned and insert before (add dependent) button. Actually I have another button outside of the div called (add applicant) and by clicking it, whole of the div would be cloned and added before (add applicant) button. my code is like this :

JavaScript
JavaScript

my problem is when i click on (add dependent) in cloned div, the row is added to main div not cloned one. hope to here you soon. Thanks a lot

Advertisement

Answer

There are many changes I made to your code and I’ll try to explain them here. When you’re working with duplicating, appending, removing etc, id’s can become difficult to work with – you can’t have duplicates of IDs and your code then has to track which id is affected by which button etc.

Its much easier to work with relative paths. For instance when you want to add a dependent, it’s easier to say ‘find a dependent input to clone and place it inside the container from where I clicked this add-dependent button’ – and walla no need for ids. To find the relative div’s, I used a combination of event.target, closest() and querySelctor – like this:

JavaScript

This says Starting from the button I clicked, find the closest ‘.add-applicant-container’ and inside that find the first ‘.dependents’ and place our clone right after that

Finally, the buttons. Because you’re creating and destroying these buttons in the process, it’s best to set up a listener on document and test to see which button was clicked. This is called event delegation. For the dependent delete button, we only need to find the relative element and delete it so:

JavaScript

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement