开发者

get text value of selected dropdown menu option using jquery

开发者 https://www.devze.com 2023-03-30 04:57 出处:网络
How can I get the text within the selected dropdown menu option using jQuery? I 开发者_运维百科have tried:

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

精彩评论

暂无评论...
验证码 换一张
取 消