在javascript中选择选项值

时间:2012-08-06 12:40:57

标签: javascript

  

可能重复:
  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>

我需要这样做:

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?

2 个答案:

答案 0 :(得分:10)

var elem = document.getElementById("short_code"),
    selectedNode = elem.options[elem.selectedIndex];

if ( selectedNode.value === "First" ) { //...

答案 1 :(得分:1)

这个怎么样:

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++)),您可以获得所需的所有信息