Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Sometimes a need arises to get the text of the selected option in a drop-down list. Using some jQuery selectors this is possible, but first lets see what doesn't work.

Lets say I have a drop-down list defined like this:
 HTML
<select class="form-control" id="groupId">
<option value="1">Administrator</option>
<option value="2">Member</option>
<option value="3">Guest</option>
<option value="4">Traveller</option>
</select>


Which looks like:
selectopt.png


If I do a naive thing such as...
 JavaScript
console.log(
$('select#groupId').text()
);


...the output is a very confusing jumble of all your option text values...
 JavaScript
AdministratorMemberGuestTraveller




Instead you have to use the :selected selector on the drop-down list option value like so...
 JavaScript
console.log
$('select#groupId option:selected').text()
);


This produces the correct output that is a single text value for the currently selection option.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.