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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10100870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:51:11  来源:igfitidea点击:

How to get the display value of Select using javascript

javascript

提问by alkhader

<Select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</Select>

I am using document.getElementById("Example").value;to get the value.

document.getElementById("Example").value;用来获取价值。

I want to display the text instead of the value. eg. value=1 --> One. How can I get the Onetext?

我想显示文本而不是值。例如。value=1 --> One. 我怎样才能得到One文本?

回答by mplungjan

In plain JavaScript you can do this:

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

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>

回答by Bhaskarreddy Mule

Here the selected text and value is getting using jquery when page load

这里选择的文本和值在页面加载时使用 jquery

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

refer this

参考这个

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

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

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

回答by Mohammed Muzammil

This works well

这很好用

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
});