Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

jQuery: Get the Selected Option Text

DZone's Guide to

jQuery: Get the Selected Option Text

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

What’s the Task?

First of all let me explain what is the task. If there’s a select menu with several options, each of which are with a given value attribute, the task is to get the text into the option tag, and not that of the value attribute.

In that scenario let’s assume that we have the following HTML:

<select id="my-select">
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>


Note that in the official jQuery doc page, the selector is described in the same context, but with a different markup:

<select id="my-select">
<option>value 1</option>
<option>value 2</option>
</select>

than the jQuery snippet looks like that:

$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});

Here’s interesting to note that there’s no value attribute set to the options, thus the selection of an element is correct and the returned value is correct. The problem is that this code doesn’t work correctly once you’ve a different value attribute, from the value enclosed into the option tag. In our case we’ve the markup shown on the first code snippet and we’d like to get the “value 2″ string instead of “2″.


Source Code

<select id="my-select">
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});

 

Solution

Finally the solution, is pretty simple and clear, but this time is not to so “native” and it’s definitely something you couldn’t expect! The only thing you’ve to do is to change the selector!

$(document).ready(function() {
$("#my-select).change(function() {
alert($('#my-select option:selected').html());
});
});

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}