Abhishek
Abhishek

Reputation: 4340

How to capture the text of an Select option?

So I have this:

<select id="list">
    <option value="1">This is Me</option>
    <option value="2">This is You</option>
    <option value="3">And this is Mr. Nukem</option>
</select>

How would I go about grabbing the 'text' of the options here? The problem is, it needs to be 'dynamic', in the sense I need the text for the currently selected option...

I know a manual, static way of getting the text...

document.getElementById('list').options[1].text

That will grab "This is You"... But how do I get it for the currently selected option? Since I can't simply use:

document.getElementById('list').value

As that will grab the number... :-(

Upvotes: 0

Views: 2020

Answers (4)

Wayne S
Wayne S

Reputation: 11

The jQuery solution is like this:

$("#list option:selected").text()

Upvotes: 0

Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

$("#list option[value='2']").text()

You can use this jQuery line and it will solve your problem.

In this an element with id list which has a property value equal to 2. What you want is the option child of the list.

Upvotes: 0

webspy
webspy

Reputation: 726

If you can use jQuery, you can try something like this:

$("#list").change(function() {
    alert($(this).find("option[value=" + $(this).val() + "]").text());
});

See http://jsfiddle.net/MWu9f/ for a working example.

Upvotes: 0

Tomalak
Tomalak

Reputation: 338218

var list = document.getElementById('list');
var text = list.options[list.selectedIndex].text;

See (for example) here https://developer.mozilla.org/en/DOM/HTMLSelectElement

Upvotes: 3

Related Questions