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
});

推荐答案

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

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

Jquery相关问答推荐

如何从 jQuery 转到 React.js?

jQuery 1.4.1 中缺少 JSON 字符串化?

jQuery从字符串中删除字符串

如何判断是否有任何 JavaScript 事件侦听器/处理程序附加到元素/文档?

JSON字符串到JS对象

jQuery增量读取AJAX流?

在不刷新页面的情况下更新网站的 CSS

jQuery中追加的相反

使用 jQuery 拖放防止单击事件

如何使用 jQuery 从 div 中删除 id 属性?

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

用 Javascript 加载 jQuery 并使用 jQuery

如何使用 JQuery 创建一个新的 img 标签,其中包含来自 JavaScript 对象的 src 和 id?

.apply jQuery 函数是什么?

与 C# HashSet 等效的 JavaScript 是什么?

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

什么时候应该使用 jQuery deferred 的then方法,什么时候应该使用pipe方法?

Select jQuery UI 自动完成后清除表单字段

通过 javascript/jquery 删除/截断前导零

更改 url 而不使用 javascript 重定向