How can I get the text within the selected dropdown menu option using 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()
Working example
Since it's not working for you, the error must lie somewhere else. Maybe #selectattribute
is incorrect.
To clarify some of the other answers, the value
of an option is different from the text
inside it.
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:
<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:
var title = $("#selectattribute :selected").text();
精彩评论