Reputation: 307
Add row will clone the div but when I continue to click it doesn't clone single element but multiples, what's the flaw of the logic here?
$('#addRow').click(function () {
$(this).siblings('.elem').clone().appendTo($(this).siblings('.elem'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elem">elem</div>
<a id="addRow">+</a>
Upvotes: 1
Views: 905
Reputation: 173532
The problem is that your .elem
selector matches more and more elements each time you click the button.
A way to resolve this is to keep a reference to one element and use that to clone and then append; additionally, it makes sense to group those elements in another <div>
for easier reference.
jQuery(function() {
var $elem = $('#rows .elem'); // keep as reference
$('#addRow').click(function () {
$('#rows').append($elem.clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rows">
<div class="elem">elem</div>
</div>
<a id="addRow">+</a>
Upvotes: 0
Reputation: 2517
You are having multiple cloning because each time the element is cloned a new element with class="elem"
is generated and hence all the elements having class="elem"
are cloned on each click.
To address this problem use first()
which only selects the first element with class="elem"
and thus only one element is cloned on each click.
Below is a simplified version of the code,
$("#addRow").click(function(){
$(".elem").first().clone().appendTo("body");
});
Here is the JSFiddle for this solution
Instead of appending it to "body" use the id of the element to which you want to append the cloned elements. Hope this helps.
Upvotes: 1
Reputation: 858
Clone only the first element and insert it just once, after the last instance.
$('#addRow').click(function () {
$(this).siblings('.elem:first').clone().insertAfter($(this).siblings('.elem:last'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elem">elem</div>
<a id="addRow">+</a>
Upvotes: 0
Reputation: 490153
You want to only select one element, and the siblings('.elem')
call is selecting all of them (except the current), including the cloned ones.
You can call first()
after you call siblings()
to select only one.
You also probably want to append them to the parent, not the same collection of all siblings.
var $clone = $(this).siblings('.elem').first().clone();
$clone.appendTo($(this).parent());
Alternatively, you could insertAfter()
the last element ($(this).siblings('.elem').last()
).
Upvotes: 2