j.Doe j.Doe - 5 months ago 11
jQuery Question

How do I clone a div contains multiple input fields more than once?

I have read few solutions in here but I still could not figure out why my

div
refuse to clone more than once.

Here is my
html
:

<h4 class="ui dividing header">Maklumat Ahli Keluarga</h4>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div class="ahli_keluarga" id="ahli_keluarga1">
<div class="field">
<label>Nama</label>
<div class="field">
<input type="text" name="shipping[first-name]" placeholder="Nama Penuh">
</div>
</div>
</div>
</div>


Here is my script:

<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum div allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var clone = $( ".ahli_keluarga:first").clone().append('<a href="#" class="remove_field">Remove</a>');

var x = 1; //initlal div count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max div allowed
x++; //div increment
$(wrapper).append(clone); //
}
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>


The cloning works but it only clone the
div
once.

Answer

You need to clone the nodes every time you click add, otherwise it's just going to reference the element that's already there. Additionally, your wrapper is already a jQuery element, so no need to wrap in a $().

Change this line:

$(wrapper).append(clone);

to

wrapper.append(clone.clone());

There's a full running snippet below if you want to see it in action.

$(document).ready(function() {
  var max_fields      = 10; //maximum div allowed
  var wrapper         = $(".input_fields_wrap"); //Fields wrapper
  var add_button      = $(".add_field_button"); //Add button ID
  var clone           = $(".ahli_keluarga:first").clone().append('<a href="#" class="remove_field">Remove</a>');

  var x = 1; //initlal div count
  $(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max div allowed
      x++; //div increment
      wrapper.append(clone.clone()); //
    }
  });

  $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); x--;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h4 class="ui dividing header">Maklumat Ahli Keluarga</h4>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div class="ahli_keluarga">
    <div class="field">
      <label>Nama</label>
      <div class="field">
        <input type="text" name="shipping[first-name]" placeholder="Nama Penuh">
      </div>
    </div>
  </div>
</div>

Comments