如何使用 javascript 获取 Select 的显示值

How to get the display value of Select using javascript

本文关键字:显示 Select 获取 何使用 javascript      更新时间:2023-09-26
<Select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</Select>

我正在使用document.getElementById("Example").value;来获取值。

我想显示文本而不是值。 value=1 --> One .如何获取One文本?

在普通的JavaScript中,你可以这样做:

const show = () => {
  const sel = document.getElementById("Example"); // or this if only called onchange
  let value = sel.options[sel.selectedIndex].value; // or just sel.value
  let text = sel.options[sel.selectedIndex].text;
  console.log(value, text);
}
window.addEventListener("load", () => { // on load 
  document.getElementById("Example").addEventListener("change",show); // show on change
  show(); // show onload
});
<select id="Example">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

j查询:

$(function() { // on load
  var $sel = $("#Example");
  $sel.on("change",function() {
    var value = $(this).val();
    var text = $("option:selected", this).text();
    console.log(value,text)
  }).trigger("change"); // initial call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Example">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

在这里,当页面加载时,所选的文本和值是使用 jquery 获取

$(document).ready(function () {
var ddlText = $("#ddlChar option:selected").text();
var ddlValue = $("#ddlChar option:selected").val();
});

参考这个

http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html

http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html

这很好用

jQuery('#Example').change(function(){ 
    var value = jQuery('#Example').val(); //it gets you the value of selected option 
    console.log(value); // you can see your sected values in console, Eg 1,2,3
});