Probably a common issue, but I’m looking for help in both fixing and understanding the issue.
I’m making a form that allows you to add more fields. Here’s a stripped down version:
HTML
<div class="to_copy">
<p>Here is an empty form field.</p>
<input name="input" />
</div>
<a href="#" id="copy">Copy</a>
jQuery
$(document).ready(function() {
var to_copy = $(".to_copy").clone();
$("#copy").on("click", function(e) {
// Some unwritten code to change name="input" to name="input1"
$(this).before(to_copy);
e.preventDefault();
});
});
When you click copy, it works once, but not any more. If I check what’s going on, the to_copy variable has the correct value, and no errors are triggered.
Can anyone explain why it doesn’t work, as well as pointing me in the right direction.
My next stage is going to be to modify the names of the fields to have a number appended to them (i.e. input, input1, input2 etc), perhaps explaining why I’ve chose this approach.
Here’s a live version: http://jsfiddle.net/nGmYb/1/
The issue is that you’re attaching the clone to the DOM within the click event. On the second click you are re-adding the element to the DOM. Try the following instead: