我的表单元素在这里:
<li><div id="formanswer1" class="clonedInput">Answer:
<input type="text" id="formanswer1" value="" /></div></li>
<li><input type="button" id="btnAdd" value="Add Answer" /></li>
<li><input type="button" id="btnDel" value="Remove Answer" /></li>
和我的jquery代码在这里:
$('#btnDel').attr('disabled','disabled');
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#formanswer' + num).clone().attr('id', 'formanswer' + newNum);
var guianswer = $('#guianswer'+num).clone().attr('id', 'guianswer' + newNum).html('Answer '+newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'formanswer' + newNum);
guianswer.children(':first').attr('id', 'guianswer' + newNum).attr('name', 'guianswer' + newNum);
// insert the new element after the last "duplicatable" input field
$('#formanswer' + num).after(newElem);
$('#guianswer' + num).after(guianswer);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 questions
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#formanswer' + num).remove();
$('#guianswer'+num).remove();
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
我在这里有一个jsfiddle:JsFiddle.net
基本上发生的事情是,当我使用按钮添加新输入时,它会复制先前的输入值。 示例:在输入1中,如果我输入“abc”然后按下添加按钮,当我想要一个值“”空白或没有值时,会出现一个值为“abc”的新输入。
任何和所有帮助都非常感谢!
答案 0 :(得分:3)
更改此行以清除该值。
newElem.children(':first').attr('id', 'formanswer' + newNum).val('');