Problem in using JQuery's clone() for text box
This is what i need to clone:
<p id="ex">
<label for="c2">Enter your Choice</label>
<br>
<input type="text" name="c2_r" id="c2" value="" />
<br>
</p>
I clone it by this statement:
$("#def").append($("#ex").clone());
As i see, it is cloning the p element. But,i actually want it to clone the p tag and set the value of textbox inside it to "". Can someone explain me what to do ? Al开发者_如何学Cso, i need to set the id of the textbox inside cloned element to be different from the original . Please help. Thanks
// first we grab the clone. We also want to change the <p>'s id, as it's
// not valid to have two elements within a page with the same ID.
$('#ex').clone().attr({
id: 'newpid' // paragraph's ID
// next, we alter the input inside it (change ID, clear value).
}).find('input').attr({
value: '',
id: 'newid' // <input>'s ID
// call end to stop the ".find", then add it to the #def element
}).end().appendTo('#def');
Working Example: http://www.jsfiddle.net/F4rRQ/1/
Here you go...
var clonedP = $('#ex').clone();
clonedP
.attr({ id: 'new_id' })
.find('input')
.attr({id: 'new_input_id'})
.val('');
$('#def').append(clonedP);
I put code in place to change their id
attribute, because an id
must be unique per page.
You will also need to change the name
attribute (i.e. different names for different inputs) if you are intending to read this data in a sane fashion.
精彩评论