Define select dropdown text with jquery $ (this)

I have several selections on the page, for example.

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

I would like to use jquery $ (this) to determine which of the several drop-down lists were selected and return their text value.

I can use something like:

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

To return the specified entry, but when I try to add $ (this) to the mix, this will not work. Where am I mistaken?

+3
source share
2 answers

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

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

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

, starts with ^ :

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

:

+12

, .val(), :

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

, :

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

$(this) , click, change ..

+2

Source: https://habr.com/ru/post/1763494/


All Articles