使用 jQuery 获取选定的选项 id

我尝试使用 jQuery 根据选中的选项发出 ajax 请求。

有没有一种使用 jQuery 检索所选 选项 ID(例如“ id2”)的简单方法?

<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
});
252590 次浏览

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

$("#my_select").change(function() {
var id = $(this).children(":selected").attr("id");
});

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

$('#my_select option:selected').attr('id');

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