Reputation: 4848
I am using jquery to clone a form input field when user click on Add button everything goes fine, but I have a problem that if I write something in form input field and click Add button, then jQuery will copy that text into new cloned input element also.
You can try a demo: http://jsbin.com/ikebil/2/edit
Steps:
Open the link and click render
Type something in input field
Click on add button it will create a new input field but also copy the text written in the previous one.
Original code: http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/
So I need to remove that text which comes if anything is written in the previous element.
Upvotes: 0
Views: 1931
Reputation: 41533
The best solution would be to actually make a copy of the element before it's being populated with any data, and then use that "safe" copy and clone it.
It's faster and safer => see working example
Upvotes: 1
Reputation: 22780
clone
copies all the attributes of element, including its value
. Just clear it explicitly after cloning if you need that:
var newElem = $("#input" + num).clone();
newElem.val("");
Upvotes: 1
Reputation: 1075885
Just use val
to clear out the cloned element. I didn't follow your links (always post the code in the question), but for instance:
var c = field.clone().val("");
That clones field
, then clears the value out of it, and assigns the clone to c
.
Update: I looked at the code, you clone the element but want to change the value on a descendant:
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
Just add .val("")
to that last line:
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum).val("");
Upvotes: 4