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

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


当前回答

如果您遇到过纯为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;

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

其他回答

只需使用

$('#SelectBoxId选项:selected').text();获取列出的文本$('#SelectBoxId').val();用于获取所选索引值

纯JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option

角度JS:(http://jsfiddle.net/qk5wwyct):

// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// JavaScript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'
}];

onChange回调中的event.target.value为我提供了诀窍。

以下是JavaScript代码行:

var x = document.form1.list.value;

假设下拉菜单名为list name=“list”,并包含在name属性name=“form1”的表单中。

在更现代的浏览器中,querySelector允许我们使用:checked伪类在一条语句中检索所选选项。从所选选项中,我们可以收集所需的任何信息:

const opt=document.querySelector(“#ddlViewBy选项:选中”);//opt现在是选定的选项,因此console.log(opt.value,'是所选值');console.log(opt.text,“是所选选项的文本”);<select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择>