2013-01-23 45 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;