I have a piece of code that clones three fields, but when it clones the three fields, it also clones the text entered inside of it, is there a way to clear the content inside of the field when it is cloned?
$(document).ready(function() {
$('#开发者_开发百科btnAdd').click(function() {
var num = $('.clonedSection').length;
var newNum = new Number(num + 1);
var newSection = $('#clonedSection' + num).clone().attr('id', 'clonedSection' + newNum);
newSection.children(':first').children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newSection.children(':nth-child(2)').children(':first').attr('id', 'age' + newNum).attr('name', 'age' + newNum);
newSection.children(':nth-child(3)').children(':first').attr('id', 'school' + newNum).attr('name', 'school' + newNum);
$('.clonedSection').last().append(newSection);
$('.clonedSection').last().val(ping);
$('#btnDel').attr('disabled','');
if (newNum == 2)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedSection').length; // how many "duplicatable" input fields we currently have
$('#clonedSection' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
Thanx in advance!
Where you're doing .clone()
you can find/clear the fields, like this:
.clone().find(':text, textarea').val('').end()
If you don't have <textarea>
elements you an leave out that bit, what this does is perform a .find()
to get the text elements, .val()
to clear them and .end()
to return the chain afterwards to using the coned element, not the text elements we were looking for.
Or, alternative, if these lines are your inputs:
newSection.children(....)
just add a .val('')
on the end of each , for example the first could look like this:
newSection.find('> :first > :first').attr({'id': 'name' + newNum, 'name': 'name' + newNum }).val('');
Just set the value
attribute to an empty string using .attr("value", "")
(I'm assuming you're talking about a <input type="text" />
):
newSection.children(':first').children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum).attr('value', '');
You can clear the input elements like this:
newSection.find(':input').val('');
精彩评论