views:

44

answers:

2

I've got several select elements on a page e.g.

<select class="dd" id="dropdown1">
    <option value="123">Option A</option>
    <option value="234">Option B</option>
</select>
<select class="dd" id="dropdown2">
    <option value="456">Option C</option>
</select>

etc etc

I would like to use jquery's $(this) to identify which of the several drop-downs have been selected and return their textual value.

I can use something like:

$("#dropdown1 :selected").text() 

To return a specified entry but when I try to add $(this) into the mix it doesn't work. Where am I going wrong?

+1  A: 

You probably want to use the .val() function which will give you the currently selected item value in the drop down list:

var selectedValue = $('#dropdown1').val();

And to get the text and not the value:

var selectedText = $('#dropdown1 option:selected').text();

$(this) is more commonly used in the context of an event handler like click, change, etc...

Darin Dimitrov
the issue here is that #dropdown2 doesn't get detected, in the real code I don't want to have to identify each of the dropdowns one-by-one
moztech
+1  A: 

Since you are using the same class for them all, you can use that:

$(".dd").change(function(){
  alert($('option:selected', $(this)).text());
});

To get the value option of the selected value, you can use the val() method instead.

Note that you can also use the starts with ^ selector like this:

$("select[id^='dropdown']").change(function(){
  alert($('option:selected', $(this)).text());
});

More Info:

Sarfraz
$('option:selected', $(this)).text() worked great for me. Many thanks
moztech