2012-08-06 89 views
-3

可能重複:
How to get the selected value of dropdownlist using JavaScript?
How to get the value of a selected text in javascript獲得期權價值的選擇在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? 
+5

你[只是問這個](http://stackoverflow.com/questions/11828125/how-to-get-the-value-of-a-selected-text-in-javascript)。如果答案不起作用,則需要澄清問題而不是重新發布。 – 2012-08-06 12:45:32

+0

@am不是我..可憐的男孩 – alkhader 2012-08-06 13:05:15

回答

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

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

這不是*真的*你會怎樣做,是嗎?這是一個很長的(也可能是容易出錯的)'做elem.options [elem.selectedIndex]'的方法。 – 2012-08-06 13:14:01

+0

啊,對不起。我錯過了這個笑話。 – 2012-08-07 11:18:42

+1

selectedNode = elem.options [elem.selectedIndex] .value; – 2015-11-04 10:12:40

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++)做),你可以得到所有的信息,你需要

+0

'無論是創建一個引用變量,就像我做過的選擇,或簡單的' - 你沒有使用它,雖然...... – andlrc 2012-08-06 12:52:17

+0

不,我沒有,但我將它包含在片段中以顯示如何引用節點列表 – 2012-08-06 13:04:02