如何从JavaScript的下拉列表中获取选定的值 [英] How to get selected value from Dropdown list in JavaScript
本文介绍了如何从JavaScript的下拉列表中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用JavaScript从下拉列表中获取选定的值?我已经尝试了以下方法,但是它不起作用.
How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
推荐答案
对我来说很好.
我有以下HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
以及以下JavaScript:
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
查看,您正在使用正确的ID.如果您将其与ASP.NET一起使用,则ID在呈现时会更改.
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
这篇关于如何从JavaScript的下拉列表中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文