Portal_Zii Portal_Zii - 1 year ago 42
jQuery Question

Cloning div on click breaks when moving the button out of container?

I found this nifty js fiddle and it does nearly exactly what I need

However its cloning the parent of the button and id like to have the button separate from the actual div being cloned. (if you put the clone button back into the container with the remove button it works fine again)

In all I am trying to accomplish 3 things.

1. Have the button outside of the div that's being duplicated (1 button)

2. Limit the number of duplication's to a total of 6. (or any changeable variable)

3. Update the

content and change the number 1 to the next number. ie: (1-6)

I'm not very JS savvy although I do dabble. If anyone has the time to help me figure out the above it would be beyond appreciated! Here's the JS FIDDLE I've been playing with.


var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;

function clone(){
.attr("id", "clonedInput" + cloneIndex)
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
function remove(){
$("button.clone").on("click", clone);

$("button.remove").on("click", remove);

Answer Source

I think the folowing is what you're trying to acheive, you have to add another variables cloned_nbr and clones_limit to control the cloned divs:

var cloneIndex = 1;
var clones_limit = 4;
var cloned_nbr = $(".clonedInput").length-1; //Exclude Default (first) div 

function clone()

    var new_clone =  $(".clonedInput").first().clone();

    new_clone.attr("id", "clonedInput" +  cloneIndex);
    new_clone.on('click', 'button.clone', clone);
    new_clone.on('click', 'button.remove', remove);

function remove(){
$("button.clone").on("click", clone);

$("button.remove").on("click", remove);
body { padding: 10px;}

.clonedInput { padding: 10px; border-radius: 5px; background-color: #def; margin-bottom: 10px; }

.clonedInput div { margin: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput1" class="clonedInput">
    <label for="txtCategory" class="">Learning category <span class="label-nbr">1</span><span class="requiredField">*</span></label>
    <select class="category" name="txtCategory[]" id="category1">
      <option value="">Please select</option>

  <div class="actions">
    <button class="remove">Remove</button>

<button class="clone">Clone</button>