Sujan Shrestha Sujan Shrestha - 5 months ago 30
Javascript Question

Duplicating and removing sections using Jquery

I have a form which i want to clone. The form looks like this.

<form method="post">
<div id=duplicator>
<div class="form-group col-md-6">
<label>Client's Name</label>
<input type="text" class="form-control" name="client_name" />
</div>
<div class="col-md-12">
<div class="pull-left">
<button type="button" class="btn btn-success add" onclick="duplicate()">ADD +</button>
<button type="button" class="btn btn-danger remove">DEL -</button>
</div>
</div>
</div>
//Duplicator div close
<div class="pull-right">
<input type="submit" class="btn btn-success btn-xm submit" name="submit" value="Submit" />
</div>
</form>


I duplicated the Division using following code:

var i = 0;
var original = document.getElementById('duplicator');

function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicat0r" + ++i;
original.parentNode.appendChild(clone);
}


But the divisions are cloning after the submit button. I want to insert the cloned div before the submit button.

and how to remove the cloned division on clicking delete button.

Answer

Use clone() to coping element and use before() to inserting element before selector.

$(".add").click(function(){
    var clone = $(".form-group:first").clone();
    clone.find("input").val("");
    $(".buttonBox").before(clone);
});

$(".remove").click(function(){
    $(".form-group:last").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=duplicator>
    <div class="form-group col-md-6">
        <label>Client's Name</label>
        <input type="text" class="form-control" name="client_name" />
    </div>
    <div class="col-md-12 buttonBox">
        <div class="pull-left">
            <button type="button" class="btn btn-success add">ADD +</button>
            <button type="button" class="btn btn-danger remove">DEL -</button>
        </div>
    </div>
</div>
<div class="pull-right">
    <input type="submit" />
</div>