Javascript 获取当前选择的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8809265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current selected option
提问by Mark Fondy
<select id="sel">
<option id="1">aa</option>
<option id="2">bb</option>
<option id="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).children().attr('id'))
})
LIVE:http://jsfiddle.net/cxWVP/
直播:http : //jsfiddle.net/cxWVP/
How can i get current selected option ID? Now always show me id="1".
如何获取当前选择的选项 ID?现在总是显示 id="1"。
回答by Jakub
$('#sel').change(function(){
alert($(this).find('option:selected').attr('id'));
});
should work.
应该管用。
回答by Esailija
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id );
})
回答by Rocket Hazmat
<option>
tags should have a value
attribute. When one is selected, you get it's value using $("#sel").val()
.
<option>
标签应该有一个value
属性。选择一个后,您可以使用$("#sel").val()
.
<select id="sel">
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).val())
});
回答by Juan Mendes
To get the selected option inside a select element, you can use selectedIndex
, then you can use the options
array to get to the selected option object
要在 select 元素中获取选定的选项,您可以使用selectedIndex
,然后您可以使用options
数组来获取选定的选项对象
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id )
})
回答by ShankarSangoli
Try this
尝试这个
$("#sel").find('option:selected').attr('id');
Ideally you should use value
attribute for option tags and just use val
method to get the selected value from the dropdown element. $("#sel").val();
理想情况下,您应该value
为选项标签使用属性,并仅使用val
方法从下拉元素中获取所选值。$("#sel").val();
回答by Badre
Try this :
尝试这个 :
$('select:#idSelect').val()
回答by simshaun
$(this).find('option:selected').attr('id')
$(this).find('option:selected').attr('id')
回答by jrummell
回答by Yogurt The Wise
Will the jquery :selected filter work. Something like this...
jquery :selected 过滤器会起作用吗?像这样的东西...
$("#sel:selected").each(function(){
alert($(this).attr('id'))
})