假设用户输入一个值,例如 5,然后打开新的下拉菜单为 5。当用户将值更新为 7 时,添加新的两个下拉菜单,但前 5 个不会删除。我该如何做到这一点?
这是关于使用表单添加文本框
function add(text){
var TheTextBox = document.forms[0].elements['field_name']; //I think that's right, haven't done it in a while
TheTextBox.value = TheTextBox.value + text;
}
<select onchange="optionChanged2(this);">
<option value="0">Hayır</option>
<option value="1">Evet</option>
</select>
我知道应该使用循环,但我不知道......
最佳答案
根据我的猜测,您希望输入最后一个数字来确定选择的选项数量,而不删除以前的选项。如果情况并非如此,请根据您的情况调整此代码片段,但您应该大致了解如何向选择添加元素。
这是 html 部分:
<input type="text" id="text">
<select id="sel">
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
JavaScript 部分:
function add(text){
var TheTextBox = document.getElementById("text");
var TheSelect = document.getElementById("sel");
var num = new Number(TheTextBox.value); // Making sure we get a number out of it
if(num > TheSelect.options.length){ // Do we have a number greater than the number of options
for(var i=0; i<(num-TheSelect.options.length); ++i){ // Add the extra options
var option = document.createElement("option");
option.setAttribute("value", i);
option.innerHTML = text;
TheSelect.appendChild(option);
}
}
else { // We have more options that we need to lets remove them from the end
for(var i=0; i<(TheSelect.options.length-num); ++i){
TheSelect.removeChild(TheSelect.options[TheSelect.options.length-1]);
}
}
}
如果这不是您想要的,请让我更具体。
关于javascript - 动态打开的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675117/