views:

92

answers:

4

If I have this select:

     <select id="days">
        <option value="0">Today</option>
        <option value="1">Yesterday</option>
        <option value="7">Last week</option>
     </select>

and someone selects the 3rd option 'last week', I can get the value of last week (which is 7), using $("#days").val(), but how can I get the value of the text i.e 'Last week'?

A: 

Add a class "myOption" to the options, and an sttribute value with the text you want. Then:

$(".myOption").each( function( i ) { if( $(this).attr('selected') ) { $(this).attr('value') } );

psychotik
+3  A: 

Does .text() not give you the result you are after?

http://marcgrabanski.com/article/jquery-select-list-values - found this too

Phill Duffy
I tried `.text()` too, but it gives me a string containing all the the options, not just the selected one
Click Upvote
ah yes, you do need to use like najmeddine suggests and make sure you only get the selected item
Phill Duffy
+6  A: 
$("#days option:selected").text()
najmeddine
A: 

Might be a little verbose (I'm sure I can remember an easier way...)

var value = $("#days").val(); 
$("option[value='" + value + "']", "#days").text()
Russ Cam