1

I have a select tag.

Here is the jquery:

$('#offer').change(
function(){
     alert($(this + "option:selected").val());
});

I want to get the value of the option:selected of this. The above code dose not work. But if I pas a id it works "#idofselecet option:selected"

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Rails beginner
  • 14,321
  • 35
  • 137
  • 257
  • The way you've written it concatenates the `this` node with the string `option:selected'`, which isn't going to return any objects. You could, if you really wanted to, use `$(this).find('option:selected').val()` (but don't, use [adeneo's suggestion](http://stackoverflow.com/a/15034445/82548), it's better and far more efficient). – David Thomas Feb 22 '13 at 22:45

2 Answers2

4

The selects value will change to whatever the text in the selected option is:

$('#offer').on('change', function() {
    alert( this.value );
});

You can also do

$('#offer').on('change', function() {
    alert( $('option:selected', this).val() );
});

This works by passing this as context to the selector, but you're adding an element, this, to a string, this + "option:selected", and that does'nt work.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • +1 But note the two examples are not equivalent in this scenario ``. Also, sticking with jQuery, the first example can also be `alert($(this).val())`. – Boaz Feb 22 '13 at 22:47
  • @martriay Typo :) Fixed. – Boaz Feb 22 '13 at 22:48
  • @Boaz - you're right, an option can have a value, and getting that value with val(), would be more proper. Most people tend to just assume the text inside the option, which is after all the text you see on the screen, is what you get with val(), so I used text(). Changed that. – adeneo Feb 22 '13 at 22:51
1

You can use the .find() method to .

The context selector uses this internally to search in the context.

$('#offer').change(function(){
     alert($(this).find("option:selected").val());
});
Sushanth --
  • 55,259
  • 9
  • 66
  • 105