[英]get text value of selected dropdown menu option using jquery
How can I get the text within the selected dropdown menu option using jQuery? 如何使用jQuery在选定的下拉菜单选项中获取文本?
I have tried: 我努力了:
var title = $("#selectattribute option:selected").text();
But I don;t think it works.. 但是我不认为这可行。
What you did should work: 您所做的应该起作用:
$("select option:selected").text()
Since it's not working for you, the error must lie somewhere else. 由于它对您不起作用,因此错误必须在其他地方。 Maybe
#selectattribute
is incorrect. 也许
#selectattribute
不正确。
To clarify some of the other answers, the value
of an option is different from the text
inside it. 为了阐明其他一些答案,选项的
value
与其内的text
不同。
For example: 例如:
<select>
<option value="red" selected="selected">Ferrari</option>
</select>
// For the above HTML
$("select option:selected").text() === 'Ferrari'
$("select option:selected").val() === 'red'
Also, if no selected
attribute is set in the HTML, the first option
will be selected: 另外,如果在HTML中未设置任何
selected
属性,则将selected
第一个option
:
<select>
<option value="black">Porsche</option>
<option value="red" >Ferrari</option>
</select>
// For the above HTML
$("select option:selected").text() === 'Porsche'
You can get the value of the select box by simply using: 您可以使用以下简单方法获得选择框的值:
var title = $("#selectattribute").val();
To get the text of the option, instead of the value
attribute: 要获取选项的文本,而不是
value
属性:
var title = $("#selectattribute :selected").text();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.