Reputation: 522
I'm creating a function that's supposed to allow to create additional similar fields for a form but the clone makes multiple duplicates instead of a single duplicate after more than once clicking example jsddile
$('.cloner').click(function() {
$('#clone_id').clone().insertAfter('.clone');
});
<div class="clone" id="clone_id">
<div>
<label>Content</label>
</div>
</div>
</div>
<span class="cloner">Cloner</span>
</div>
Upvotes: 1
Views: 531
Reputation: 96
Cloner function rewritten:
$('.cloner').click(function() {
$('.clone:first').clone().insertAfter('.clone:last');
});
Explanation: Your code duplicates element IDs which is not good in the first place. If you switch to selecting class instead, you have to make sure you choose one element (:first) and that you insert it after one element (:last) and not after every element with class .clone.
Upvotes: 0
Reputation: 163
In your example you see that you are cloning the entire div where you insert the other clones so basically you are duplicating all the close that you have made.
The right solution is to take the single div inside the #clone-id div and duplicate it. That's the result
https://jsfiddle.net/zq565hsk/
$('.cloner').click(function() {
$('#clone_id').find('div').clone().insertAfter('.clone');
});
Upvotes: 0
Reputation: 337560
You have two issues to fix. Firstly you're duplicating the id
of the cloned element. You can use removeAttr()
to remove the id
on the new element.
To fix the actual duplication you need to specify that you want to only insertAfter()
the last .clone
element, not insert after all of them. Try this:
$('.cloner').click(function() {
$('#clone_id').clone().removeAttr('id').insertAfter('.clone:last');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-4">
<div class="clone" id="clone_id">
<div>
<label>Content</label>
</div>
</div>
</div>
<span class="cloner">Cloner</span>
</div>
Upvotes: 4