identify select drop-down text using jquery $(this)

15,575

Solution 1

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:

Solution 2

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

Share:
15,575
moztech
Author by

moztech

Web Developer (primarily PHP), server admin and techie based in East Sussex, UK

Updated on June 04, 2022

Comments

  • moztech
    moztech almost 2 years

    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?