如何使用JavaScript从下拉列表中获取所选值?

<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>


当前回答

运行示例:

var e=document.getElementById(“ddlViewBy”);var val1=e.options[e.selectedIndex].value;var txt=e.options[e.selectedIndex].text;document.write(“<br/>所选选项值:”+val1);document.write(“<br/>所选选项文本:”+txt);<select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”>test2</option><option value=“3”selected=“selected”>test3</option></选择>

注意:下拉列表更改时,值不会更改,如果您需要该功能,则需要执行onClick更改。

其他回答

2015年,在Firefox中,以下功能同样有效。

e.options.selected索引

var strUser = e.options[e.selectedIndex].value;

这是正确的,应该为您提供值。是你想要的文本吗?

var strUser = e.options[e.selectedIndex].text;

所以你对术语很清楚:

<select>
    <option value="hello">Hello World</option>
</select>

此选项具有:

索引=0值=hello文本=你好世界

<select name="test" id="test" >
    <option value="1" full-name="Apple">A</option>
    <option value="2" full-name="Ball">B</option>
    <option value="3" full-name="Cat" selected>C</option>
</select>

var obj  = document.getElementById('test');
obj.options[obj.selectedIndex].value;  //3
obj.options[obj.selectedIndex].text;   //C
obj.options[obj.selectedIndex].getAttribute('full-name'); //Cat
obj.options[obj.selectedIndex].selected; //true

初学者可能希望使用NAME属性而不是ID属性访问select中的值。我们知道所有表单元素都需要名称,甚至在获得id之前。

因此,我将添加getElementsByName()解决方案,让新开发人员也能看到。

没有。表单元素的名称需要是唯一的,以便表单在发布后可以使用,但DOM可以允许多个元素共享名称。因此,如果可以,请考虑将ID添加到表单中,或者使用表单元素名称my_nth_select_named_x和my_nth_text_input_named_y显式添加ID。

使用getElementsByName的示例:

var e = document.getElementsByName("my_select_with_name_ddlViewBy")[0];
var strUser = e.options[e.selectedIndex].value;

Use:

<select id="Ultra" onchange="alert(this.value)">
    <option value="0">Select</option>
    <option value="8">text1</option>
    <option value="5">text2</option>
    <option value="4">text3</option>
</select>

从元素内部访问任何输入/表单字段时,都可以使用“this”关键字。这样就不需要在DOM树中查找表单,然后在表单中查找该元素。