How to get $(this) selected option in jQuery?

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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();
});

Solution 4 - Javascript

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

Solution 5 - Javascript

This should work:

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

Solution 6 - Javascript

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();

Solution 7 - Javascript

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/

Solution 8 - Javascript

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...

Solution 9 - Javascript

It's just

$(this).val();

I think jQuery is clever enough to know what you need

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB SevenView Question on Stackoverflow
Solution 1 - JavascriptjorgebgView Answer on Stackoverflow
Solution 2 - Javascriptuser56reinstatemonica8View Answer on Stackoverflow
Solution 3 - JavascriptangelmediaView Answer on Stackoverflow
Solution 4 - JavascriptSatyam KhatriView Answer on Stackoverflow
Solution 5 - JavascriptHe ShimingView Answer on Stackoverflow
Solution 6 - JavascriptPlatinum AzureView Answer on Stackoverflow
Solution 7 - JavascriptthomthomView Answer on Stackoverflow
Solution 8 - JavascriptLikwid_TView Answer on Stackoverflow
Solution 9 - JavascriptEdmund AdjeiView Answer on Stackoverflow