user3500593 user3500593 - 2 months ago 9
jQuery Question

I'm getting multiple cloned items with jquery, what is best way to use it in a dynamic loop?

I want to clone a div based on the user input. If user inputs 1, div gets copied 1 time, if user inputs 2, div gets copied 2 times (and previously copied div gets removed of course).

This is my code:

$('input').keyup(function() {

var dtotal = parseInt($('input').val());
var $dragcont = $('#parent');
var $dragon = $("#child:not('.cloned')");

for(var i=0;i < dtotal; i++){
$dragon.clone().addClass('cloned').appendTo($dragcont);
}


I have achieved this with php (form action) but in this case I'm not allowed to fiddle with server side. Help.

JSfiddle

Answer

First of all, try not to use id on a div that will be copied. Id is suppose to be unique, so I've changed it to a class instead.

$('input').keyup(function() {
  var dtotal = parseInt($('input').val());
  var $dragcont = $('#parent');
  var $dragon = $(".child:not('.cloned')");
  
  // If you want to remove previously copied.
  $dragcont.find('.child.cloned').remove();
  
  for(var i=0 ;i <dtotal; i++){
    var $el = $dragon.clone().addClass('cloned');
    $el.appendTo($dragcont);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <p class="child">Clone me</p>
</div>  
  <input type="text"/>