在javascript中获取select中的选项值

Get the option value in select in javascript

本文关键字:选项 获取 javascript select      更新时间:2023-09-26

可能重复:
如何使用JavaScript获取dropdownlist的选定值
如何在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>

我需要这样做:

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?
var elem = document.getElementById("short_code"),
    selectedNode = elem.options[elem.selectedIndex];
if ( selectedNode.value === "First" ) { //...

这个怎么样:

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

循环浏览所有选项(创建一个引用变量,就像我对options所做的那样,或者创建一个普通的for (var i=0;i<select.options.length;i++)),您可以获得需要的所有信息