在 javascript 中的 select 中获取选项值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11828485/
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 the option value in select in javascript
提问by alkhader
Possible Duplicate:
How to get the selected value of dropdownlist using JavaScript?
How to get the value of a selected text in javascript
<select id="short_code">
<option value="12">First</option>
<option value="11">Second</option>
<option value="10">Third</option>
<option value="9">Fourth</option>
</select>
I need to do this:
我需要这样做:
if(document.getElementById("short_code").options.item(document.getElementById("short_code").selectedIndex).text)== "First")
//get the value of the option Fist , how to get the value?
回答by andlrc
var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
if ( selectedNode.value === "First" ) { //...
回答by Elias Van Ootegem
How about this:
这个怎么样:
var select = document.getElementById('short_code');
var options = select.options;
var selected = select.options[select.selectedIndex];
//which means that:
console.log(selected.value || selected.getAttribute('value'));//should log "12"
console.log(selected.innerHTML);//should log(First);
Loop through all the options (either creating a reference variable, like I did with options
, or plain for (var i=0;i<select.options.length;i++)
) and you can get all info you need
遍历所有选项(创建参考变量,就像我对options
或 plain所做的那样for (var i=0;i<select.options.length;i++)
),您可以获得所需的所有信息