javascript 查找 <select> 中选择了哪个 <Option>(没有 JQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14333797/
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-10-26 21:19:55  来源:igfitidea点击:

Finding which <Option> is selected in <select> (without JQuery)

javascripthtmlcss-selectors

提问by Guy Korland

I have the following Element:

我有以下元素:

<select id="color" name="colorId" class="btn secondary">
    <option value="347366" selected="selected">Purple</option>
    <option value="56634">White</option>
</select>

And I want to find which option is selected:

我想找到选择了哪个选项:

The following give me only the default:

下面只给我默认值:

document.querySelector('#color option[selected="selected"]')

(I know how to do it with JQuery but, I can't use jQuery or any other similar library)

(我知道如何使用 JQuery 但我不能使用 jQuery 或任何其他类似的库)

回答by Seifu

Use the :checked selector. This applies to checkbox, radio, and select

使用 :checked 选择器。这适用于复选框、单选和选择

document.querySelector('#color option:checked')

for the node

对于节点

document.querySelector('#color option:checked').value

for the value

对于价值

回答by Fabrizio Calderan

In plain javascript:

在普通的javascript中:

var select = document.getElementById('color');
var currentOpt = select.options[select.selectedIndex]; 

JsBin example: http://jsbin.com/ogunet/1/edit(open your js console)

JsBin 示例:http://jsbin.com/ogunet/1/edit (打开你的 js 控制台)

回答by Anand G

This will return selected option value and text both.. Hope this will work for u ..

这将返回选定的选项值和文本。希望这对你有用..

Cheers

干杯

var elt = document.getElementById('color');

 // get option selected
    var option = elt.options[elt.selectedIndex].value;
    var optionText = elt.options[elt.selectedIndex].text;

回答by Sirko

Grab the <select>DOMelement using getElementById()and take its parameter selectedIndex:

抓住<select>DOM使用元素getElementById(),并采取它的参数selectedIndex

var select = document.getElementById( 'color' ),
    selIndex = select.selectedIndex;,
    selElement = select.getElementsByTagName( 'option' )[ selIndex ];

回答by reno184

You can do this with querySelectorAllnot querySelector

你可以做到这一点querySelectorAllquerySelector

document.querySelectorAll('option:checked')[0].innerText

or

或者

document.querySelectorAll('option:checked')[0].value