开发者

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

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 s开发者_JS百科everal 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?


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:

  • http://api.jquery.com/val/
  • http://api.jquery.com/attribute-starts-with-selector/


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜