Javascript 如何获取Javascript选择框的选定文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3170648/
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
How to get Javascript Select box's selected text
提问by Aajahid
This things works perfectly
这东西完美运行
<select name="selectbox" onchange="alert(this.value)">
But I want to select the text. I tried in this way
但我想选择文本。我试过这种方式
<select name="selectbox" onchange="alert(this.text)">
It shows undefined. I found how to use DOM to get text. But I want to do this in this way, I means like using just this.value.
它显示未定义。我找到了如何使用 DOM 来获取文本。但我想以这种方式做到这一点,我的意思是只使用 this.value。
回答by Delan Azabani
this.options[this.selectedIndex].innerHTML
should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the valueattribute.
应该为您提供所选项目的“显示”文本。this.value,就像你说的,只提供value属性的值。
回答by Oded
In order to get the value of the selected item you can do the following:
为了获取所选项目的值,您可以执行以下操作:
this.options[this.selectedIndex].text
Here the different optionsof the select are accessed, and the SelectedIndexis used to choose the selected one, then its textis being accessed.
这里options访问的SelectedIndex是select的不同点,用来选择被选中的那个,然后它text被访问了。
Read more about the select DOM here.
在此处阅读有关 select DOM 的更多信息。
回答by Andre Morata
Please try this code:
请试试这个代码:
$("#YourSelect>option:selected").html()
回答by Marvil Joy
Just use
只需使用
$('#SelectBoxId option:selected').text();For Getting text as listed
$('#SelectBoxId option:selected').text();获取列出的文本
$('#SelectBoxId').val();For Getting selected Index value
$('#SelectBoxId').val();获取选定的索引值
回答by Michiel
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
我知道这里没有人要求 jQuery 解决方案,但值得一提的是,使用 jQuery,您可以只要求:$('#selectorid').val()
回答by Michael Albers
If you want to get the value, you can use this code for a select element with the id="selectBox"
如果要获取值,可以将此代码用于 id="selectBox" 的 select 元素
let myValue = document.querySelector("#selectBox").value;
If you want to get the text, you can use this code
如果要获取文本,可以使用此代码
var sel = document.getElementById("selectBox");
var text= sel.options[sel.selectedIndex].text;

![Javascript 预期 [ ] 为 [ ] Jasmine,如何检查空数组](/res/img/loading.gif)