使用 JavaScript 在下拉列表中获取所选值

2022-08-29 21:51:39

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

<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>

答案 1

给定一个如下所示的选择元素:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

运行此代码:

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

结果在:

value == 2
text == "test2"

交互式示例:

var e = document.getElementById("ddlViewBy");
function onChange() {
  var value = e.value;
  var text = e.options[e.selectedIndex].text;
  console.log(value, text);
}
e.onchange = onChange;
onChange();
<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>

答案 2

Plain 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

AngularJS: (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'
}];