0

在输入文本框的值并单击添加按钮后,如何在选择框(下拉菜单)中选择我新添加的值?

<html>
  <head>
    <script>
      function addref(value) {
        var x = document.getElementById("thebox");
        var option = document.createElement("option");
        option.text = value
        x.add(option,x.options[null])
      }
    </script>
  </head>
  <body>
    <form>
      <select id="thebox">
      </select>
    </form>
    <br>
    <input type="text" id="theinput"/>
    <input type="button" value="Add" name="B1" onclick="addref(document.getElementById('theinput').value)"/>
  </body>
</html>
4

2 回答 2

0

尝试这个:

x.selectedIndex = x.options.length - 1;

在此之后,您可以使用检索值

var val = x.value;

或者

var val = x[x.selectedIndex].value;

<select>在 MDN 上

此外,而不是x.add(option,x.options[null])简单地使用x.add(option). 这会将新创建option的添加到options. 第二个参数应该是一个整数,它表示添加新选项的索引位置。

于 2013-01-25T17:08:12.767 回答
0

要获取所选值,请使用以下命令:

var e = document.getElementById("thebox");
var theValue = e.options[e.selectedIndex].value;

要获取选定的文本,请使用以下命令:

var e = document.getElementById("thebox");
var theText = e.options[e.selectedIndex].text;

如果它是动态添加的,则无关紧要。

于 2013-01-25T17:15:21.640 回答