Hun*_*ain 0 html javascript css forms jquery
我会尝试尽可能具体.我有一个下拉菜单[select tag],它允许用户选择5个选项; 即数字从1到5.现在,根据所选的选项,我想显示一个新的表单,其输入标签的数量与选择的选项相同
因此,如果用户从下拉菜单中选择3,则底部将显示一个子表,显示三个输入标签.代码是:
<select id="formName9" name="blockUnits">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Run Code Online (Sandbox Code Playgroud)
您将使用on change事件侦听器:
$('select#formName9').on('change', function() {
/* Remove the existing input container, if it exists. */
$('form#container').remove();
/* Get the selected value and create the new container. */
var val = $(this).val()
$container = $('<form id="container"></form>');
/* Loop through creating input elements based on value. */
for(i=0;i<val;i++)
{
/* Create the new input element. */
var $input = $('<input type="text"/>');
/* Append this input element to the container. */
$input.appendTo($container);
}
/* Add container to the page. */
$container.insertAfter($(this));
})
Run Code Online (Sandbox Code Playgroud)
然后,您可以对此进行扩展,以根据最初selected选项添加默认输入:
我支持James Donnelly的回答.如果您希望它是纯Java脚本,您可以使用此替代方法.
HTML
<select id="formName9" name="blockUnits" onchange="addInput()">
<option selected="selected" value="1" >1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<form>
<div id="newAdd"> </div>.
</form>
Run Code Online (Sandbox Code Playgroud)
JAVASCRIPT
function addElement() {
var element = document.createElement("input"); //creating input
element.setAttribute("value", "");//setting its value
element.setAttribute("name", "newInput");//naming the input
var foo = document.getElementById("newAdd");
foo.appendChild(element);//appendign the value into the parant div
}
function addInput(){
document.getElementById("newAdd").innerHTML="";//clearing the div
var noInp=parseInt(document.getElementById("formName9").value);
while(noInp>0)
{
addElement();
noInp--;
}
}
Run Code Online (Sandbox Code Playgroud)
这是JSFIDDLE
| 归档时间: |
|
| 查看次数: |
3251 次 |
| 最近记录: |