简体   繁体   中英

get text value of selected dropdown menu option using jquery

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM