动态打开下拉菜单

时间:2013-07-16 11:17:46

标签: 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>

我知道应该使用循环,但我不知道......

1 个答案:

答案 0 :(得分:0)

根据我的猜测,您希望输入最后一个数字来确定选择的选项数量而不删除之前的选项。如果不是这种情况,请根据您的情况调整此片段,但您应该大致了解如何向选择中添加元素。

这是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]);
        }
   }
}

如果这不是你想要的,那么你将会更具体。

相关问题