javascript - 动态打开的下拉菜单

标签 javascript forms loops

假设用户输入一个值,例如 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/

相关文章:

javascript - google.maps.Circle 捕捉到最近的英里

javascript - 使用 .getJSON 从 php 文件检索 JSON 数据

javascript - 检查 javascript 数组中的最后一项

c# - 这是使用 goto 的安全方法吗?

java - 在循环中声明多个变量

javascript - iframe 并未在所有 IE 版本中完全加载

javascript - 如何在 HTML 的下拉列表中设置条件?

javascript - 填写并添加选择选项并与数据库同步

php - 表单提交发送其他元素属性?

c# - ASP.NET MVC 4 : How to update model from view on submit form