I'm trying to use JavaScript to create copies of a div element when a button is clicked. I'm using the .cloneNode() method, but it's multiplying the results.
Initially there is one instance of the element on the page; on click that doubles to 2, however on the next click it doubles again to 4. I need it to add individually, so click->3,click->4, etc.
My codepen is: https://codepen.io/anon_guy/pen/VMZWWW
HTML:
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-4">
<label>name</label>
<input type="text" name="name" value="name" placeholder="name" id="name" class="form-control" />
</div>
<div class="col-sm-4">
<label>address</label>
<input type="text" name="address" value="address" placeholder="address" id="address" class="form-control" />
</div>
<div class="col-sm-4">
<label>phone</label>
<input type="text" name="phone" value="phone" placeholder="phone" id="phone" class="form-control" />
<div class="text-danger"></div>
</div>
</form>
</div>
<div class="row">
<div class="add_component">
<button id='launch'>Add Component</button>
</div>
</div>
</div>
<div class="wrapper">
<div class="panel panel-default " id="addon">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-6">
<label>component</label>
<input type="text" name="component" value="component" placeholder="component" id="component" class="form-control" />
</div>
</form>
</div>
</div>
</div>
JS:
document.getElementById('launch').onclick = function() {
var addOnDiv = document.getElementById('addon');
var clonedNode = addOnDiv.cloneNode(true);
addOnDiv.appendChild(clonedNode );
}
This happens because
cloneNodeclones both the node as well as any children that it includes.After you clone the
addondiv, you then append your new clone to the child ofaddon. Therefore, it is now part of addon and both nodes will be copied in each subsequent add.The easiest fix is to just append the cloned node as a sibling of
addoninstead of as a child. You simply need to changeto
in your JS file