2013-01-23 42 views
0

可能重複:
How to get the selected value of dropdownlist using JavaScript?
javascript selected valueDOM找到當前選擇的下拉元素

我有一個下拉列表的數量,就像這樣:

<select id="Quantity" name="Quantity" class="quantity_select"> 
    <option id="1" selected="selected" value="1">1</option> 
    <option id="2" value="2">2</option> 
    <option id="3" value="3">3</option> 
</select> 

我需要使用JavaScript來鰭d當前選定數量的值。當我選擇例如選項2,selected =「selected」不會更改爲新選項。我如何使用DOM獲取當前選擇的數量?

感謝

+0

如果您在發佈此問題之前嘗試了一些代碼,請分享。對於這個邏輯,SO本身有很多問題 –

回答

5

選項1

HTML

<select id="Quantity" name="Quantity" 
     class="quantity_select" onchange="SetValue(this.value)> 
    <option id="1" selected="selected" value="1">1</option> 
    <option id="2" value="2">2</option> 
    <option id="3" value="3">3</option> 
</select> 

的JavaScript

function SetValue(val) { 
    alert(val); // This will be the selected value in the drop down 
} 

選項2

如果你已經有JS的地方,又不想使用選項1,你可以簡單地得到與getElementById()值:

var ddl = document.getElementById('Quantity'); 
var val = ddl.options[ddl.selectedIndex].value; 
2

使用document.getElementById('Quantity').value

2

使用

document.getElementById('Quantity').options[document.getElementById('Quantity').selectedIndex].value;