【发布时间】:2011-03-16 15:22:48
【问题描述】:
我想要一个表单输入,可以输入一个数字并单击它旁边的按钮,这样它就会“添加”以前的输入数量,每个输入都有自己的名称。
- 输入号码
- 单击“Go”按钮或其他任何内容
- 与输入数量相同的页面上的输出(创建新输入)
我已经尝试过,它只提供一次添加一个功能:
$(function() {
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
<a href="#" id="add">Add</a>
<a href="#" id="remove">Remove</a>
<input type="text" value="1" />
【问题讨论】:
-
只是
inputs?还是input加上label?input元素的类型是什么? -
我已经添加了我尝试过的内容。我正在使用 php,所以我需要 name 字段和 type="text"。
-
@ToddN:你的代码有什么问题?看起来它会起作用。
-
@Rocket 它工作得很好,但是如果我想要 20 个输入框,我必须点击它 20 次,我宁愿有一个输入框来输入我的表单中需要多少个框。