javascript – jQuery Get Selected Option From Dropdown

javascript – jQuery Get Selected Option From Dropdown

For dropdown options you probably want something like this:

var conceptName = $(#aioConceptName).find(:selected).text();

The reason val() doesnt do the trick is because clicking an option doesnt change the value of the dropdown–it just adds the :selected property to the selected option which is a child of the dropdown.

Set the values for each of the options

<select id=aioConceptName>
    <option value=0>choose io</option>
    <option value=1>roma</option>
    <option value=2>totti</option>
</select>

$(#aioConceptName).val() didnt work because .val() returns the value attribute. To have it work properly, the value attributes must be set on each <option>.

Now you can call $(#aioConceptName).val() instead of all this :selected voodoo being suggested by others.

javascript – jQuery Get Selected Option From Dropdown

I stumbled across this question and developed a more concise version of Elliot BOnnevilles answer:

var conceptName = $(#aioConceptName :selected).text();

or generically:

$(#id :pseudoclass)

This saves you an extra jQuery call, selects everything in one shot, and is more clear (my opinion).

Leave a Reply

Your email address will not be published.