19

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'?

Ali
  • 261,656
  • 265
  • 575
  • 769

5 Answers5

22
$("#days option:selected").text()
manji
  • 47,442
  • 5
  • 96
  • 103
3

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

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

Phill Duffy
  • 2,805
  • 3
  • 33
  • 45
  • I tried `.text()` too, but it gives me a string containing all the the options, not just the selected one – Ali Sep 07 '09 at 21:41
  • 1
    ah yes, you do need to use like najmeddine suggests and make sure you only get the selected item – Phill Duffy Sep 07 '09 at 21:43
0

I prefer using:

var s = $("#days");
var i = s.prop("selectedIndex"); //get selected indexs
s.children().eq(i).text(); 
Daidai
  • 547
  • 4
  • 13
0

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
  • 38,153
  • 34
  • 100
  • 135
0

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
  • 124,184
  • 33
  • 204
  • 266