user3500593 user3500593 - 9 months ago 38
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++){

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



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.
  for(var i=0 ;i <dtotal; i++){
    var $el = $dragon.clone().addClass('cloned');
<script src=""></script>
<div id="parent">
  <p class="child">Clone me</p>
  <input type="text"/>