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

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


当前回答

在更现代的浏览器中,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></选择>

其他回答

另一种解决方案是:

document.getElementById('elementId').selectedOptions[0].value

纯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'
}];

有两种方法可以使用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'

只需使用

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

我认为您可以将事件侦听器附加到select标记本身,例如:

<script>
  document.addEventListener("DOMContentLoaded", (_) => {
    document.querySelector("select").addEventListener("change", (e) => {
      console.log(e.target.value);
    });
  });
</script>

在这种情况下,您应该确保所有选项都有一个value属性,并且它们不为空。