113

The following code works:

$("#select-id").change(function(){
  var cur_value = $('#select-id option:selected').text();
  . . .
});

How to refactor the second line to:

var cur_value = $(this).***option-selected***.text();

What do you use for ***option-selected***?

B Seven
  • 42,103
  • 65
  • 226
  • 370

9 Answers9

135

For the selected value: $(this).val()

If you need the selected option element, $("option:selected", this)

jorgebg
  • 6,392
  • 1
  • 20
  • 31
  • This selector provides a jQ object, so add `.text()` gets its text [`$("option:selected", this).text()`] – gordon Dec 04 '21 at 00:23
123
 $(this).find('option:selected').text();
user56reinstatemonica8
  • 30,046
  • 19
  • 95
  • 117
  • This worked perfectly for me - I tried `$("option:selected", this)` as mentioned above but that was problematic. I was using a button click to append the selected option element text to another div, but when I clicked the button, it actually changed the selected element... weird. Use this one. – skwidbreth Apr 04 '16 at 21:30
61

Best and shortest way in my opinion for onchange events on the dropdown to get the selected option:

$('option:selected',this);

to get the value attribute:

$('option:selected',this).attr('value');

to get the shown part between the tags:

$('option:selected',this).text();

In your sample:

$("#select-id").change(function(){
  var cur_value = $('option:selected',this).text();
});
angelmedia
  • 927
  • 8
  • 10
48
var cur_value = $('option:selected',this).text();
Alex Jolig
  • 12,826
  • 19
  • 125
  • 158
Satyam Khatri
  • 481
  • 4
  • 4
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Enamul Hassan Apr 03 '16 at 03:32
14

This should work:

$(this).find('option:selected').text();
Code Maverick
  • 19,661
  • 10
  • 58
  • 112
He Shiming
  • 5,527
  • 4
  • 36
  • 64
9

You can use find to look for the selected option that is a descendant of the node(s) pointed to by the current jQuery object:

var cur_value = $(this).find('option:selected').text();

Since this is likely an immediate child, I would actually suggest using .children instead:

var cur_value = $(this).children('option:selected').text();
Platinum Azure
  • 43,544
  • 11
  • 104
  • 132
7
var cur_value = $(this).find('option:selected').text();

Since option is likely to be immediate child of select you can also use:

var cur_value = $(this).children('option:selected').text();

http://api.jquery.com/find/

thomthom
  • 2,836
  • 1
  • 22
  • 52
0

Best guess:

var cur_value = $('#select-id').children('option:selected').text();

I like children better in this case because you know you're only going one branch down the DOM tree...

Likwid_T
  • 2,828
  • 21
  • 40
0

It's just

$(this).val();

I think jQuery is clever enough to know what you need

David Buck
  • 3,594
  • 33
  • 29
  • 34