我有一个选择框:
<select id="steps_number">
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
现在,如果用户选择“4”,则需要在页面中添加4个输入框,如果他将选择更改为8,则需要有8个输入框,依此类推...
而且,输入框名称很重要,我要将表单值发送到另一个页面进行处理并将数据插入数据库,我如何知道/获取新创建的输入框名称?
最佳答案
非常简单的示例(也 demonstrated here ):
// bind to when the drop-down list changes
$('#steps_number').change(function(){
// find out the number to display
var count = $(this).val();
// Try to keep the fields already on the page. Remove anything
// that exceeds the count
$('#steps input:gt('+(count-1)+')').remove();
// But if it doesn't have enough, add more
for (var i = $('#steps input').length; i < count; i++){
$('<input>',{type:'text',id:'step'+(i+1),name='step'+(i+1)}).appendTo('#steps');
}
});
这假设您希望输入具有以下结构:
<div id="steps">
<input type="text" id="step1" name="step1" />
<input type="text" id="step2" name="step2" />
<input type="text" id="step3" name="step3" />
<!-- .... -->
</div>
对于服务器端,您现在将看到使用 $_REQUEST['step1']
、$_REQUEST['step2']
等的输入。或者,根据您的表单方法,它们也会显示在 $_POST
或 $_GET
中。
关于javascript - 根据选择框值添加多个输入框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10141033/