11
<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文本?

4

3 回答 3

29

在纯 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>

jQuery:

$(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>

于 2012-04-11T06:22:22.193 回答
2

此处选择的文本和值在页面加载时使用 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

于 2012-04-11T06:28:33.903 回答
0

这很好用

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
});
于 2019-02-02T06:04:21.207 回答