Samuel Muiruri Samuel Muiruri - 2 months ago 6
jQuery Question

Jquery duplicate making more multiple duplicates with each duplication

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>

Answer

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>