Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery clone div every time clicked

I have a simple form and with a button to clone my form when clicked. The problem is that when I click in button for the first time, it works correct, but for the next times it append many divs when clicked. Is there any way to copy one by one every time clicked? here is my snippet:

$(document).ready(function() {
    $(".Add").click(function() {
        $(".formi").clone().insertAfter(".formi:last");
    });
});
.formi {
    border: 1px solid #000;
    width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<span class="Add">Add+</span>
<div class="all">
    <form class="formi">
        <input type="text" placeholder="name" />
        <select name="cars">
            <option value="">one</option>
            <option value="">two</option>
        </select>
        <button type="submit">ok</button>
    </form>
</div>
like image 692
inaz Avatar asked Dec 19 '16 07:12

inaz


1 Answers

You can find the first form instead of finding all in the DOM using eq(0) or find the recent one ,

$(document).ready(function(){
    $(".Add").click(function(){
		  $(".formi").eq(0).clone().insertAfter(".formi:last");
//$(".formi:last").clone().insertAfter(".formi:last");
    });
});
.formi{border:1px solid #000;width:50%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<span class="Add">Add+</span>
<div class="all">
<form class="formi">
<input type="text" placeholder="name"/>
<select name="cars">
<option value="">one</option>
<option value="">two</option>
</select>
<button type="submit">ok</button>
</form>
</div>
like image 80
ScanQR Avatar answered Sep 21 '22 23:09

ScanQR