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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:36:48  来源:igfitidea点击:

Get current selected option

javascriptjqueryhtml

提问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

http://jsfiddle.net/cxWVP/1/

http://jsfiddle.net/cxWVP/1/

$("#sel").change(function(){
   alert( this.options[this.selectedIndex].id );
})

回答by Rocket Hazmat

<option>tags should have a valueattribute. 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())
});

DEMO: http://jsfiddle.net/yPYL5/

演示:http: //jsfiddle.net/yPYL5/

回答by Juan Mendes

http://jsfiddle.net/ugUYA/

http://jsfiddle.net/ugUYA/

To get the selected option inside a select element, you can use selectedIndex, then you can use the optionsarray 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 valueattribute for option tags and just use valmethod 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

Change the id attribute to value and then use .val().

将 id 属性更改为 value,然后使用.val().

<select id="sel">
    <option value ="1">aa</option>
    <option value ="2">bb</option>
    <option value ="3">cc</option>
</select>


var selectedValue = $("#sel").val();

回答by Yogurt The Wise

Will the jquery :selected filter work. Something like this...

jquery :selected 过滤器会起作用吗?像这样的东西...

$("#sel:selected").each(function(){
   alert($(this).attr('id'))
})