Get the selected option id with jQuery

2019-01-13 07:11发布

I'm trying to use jQuery to make an ajax request based on a selected option.

Is there a simple way to retrieve the selected option id (e.g. "id2") using jQuery?

<select id="my_select">
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>


$("#my_select").change(function() {
    //do something with the id of the selected option
});

4条回答
男人必须洒脱
2楼-- · 2019-01-13 07:33

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});
查看更多
闹够了就滚
3楼-- · 2019-01-13 07:37
$('#my_select option:selected').attr('id');
查看更多
SAY GOODBYE
4楼-- · 2019-01-13 07:39

var id = $(this).find('option:selected').attr('id');

then you do whatever you want with selectedIndex

I've reedited my answer ... since selectedIndex isn't a good variable to give example...

查看更多
对你真心纯属浪费
5楼-- · 2019-01-13 07:39

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

查看更多
登录 后发表回答