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

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


当前回答

有两种方法可以使用JavaScript或jQuery完成此操作。

JavaScript:

var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;

alert (getValue); // This will output the value selected.

OR

var ddlViewBy = document.getElementById('ddlViewBy');

var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;

var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;

alert (value); // This will output the value selected

alert (text); // This will output the text of the value selected

jQuery:

$("#ddlViewBy:selected").text(); // Text of the selected value

$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'

其他回答

如果您遇到过纯为Internet Explorer编写的代码,您可能会看到:

var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;

在Firefox等中运行上述命令会导致“不是函数”错误,因为Internet Explorer允许您使用()而不是[]:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

正确的方法是使用方括号。

对于如何实现这一点,我有一点不同的看法。我通常使用以下方法(这是一种更简单的方法,而且据我所知,它适用于所有浏览器):

<select onChange="functionToCall(this.value);" id="ddlViewBy">
  <option value="value1">Text one</option>
  <option value="value2">Text two</option>
  <option value="value3">Text three</option>
  <option value="valueN">Text N</option>
</select>

Try

ddlViewBy.value                      // value

ddlViewBy.selectedOptions[0].text    // label

console.log(ddlViewBy.value);console.log(ddlViewBy.selectedOptions[0].text);<select id=“ddlViewBy”><option value=“1”>快乐</option><option value=“2”>树</option><option value=“3”selected=“selected”>朋友</option></选择>

只需执行:document.getElementById('dselect').options.selectedIndex

然后,您将获得从0开始的select索引值。

您应该使用querySelector来实现这一点。这也规范了从表单元素获取值的方式。

var dropDownValue=document.querySelector('#ddlViewBy').value;

小提琴:https://jsfiddle.net/3t80pubr/