如何使用JavaScript从下拉列表中选择值?我尝试了以下,但它不起作用。如何从JavaScript中的下拉列表中获取选定的值
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
如何使用JavaScript从下拉列表中选择值?我尝试了以下,但它不起作用。如何从JavaScript中的下拉列表中获取选定的值
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:
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结合使用,则该代码会在呈现时发生变化。
直接value
应该只是罚款:
var sv = sel.value;
alert(sv);
你的代码可能会失败的唯一原因是在没有选择的项,然后selectedIndex
返回-1,代码中断。
不是它不工作 – 2012-01-12 09:07:13
看到我有下拉,我选择一个项目,并试图显示它使用警报,但不工作警报是空的 – 2012-01-12 09:08:05
代码必须在一些事件处理程序,只是让它躺在不会帮助。发布更多的代码,我们会看到你做错了什么。 – 2012-01-12 09:19:21
我会说改变var sv = sel.options [sel.selectedIndex] .value; to var sv = sel.options [sel.selectedIndex] .text;
它为我工作。指导你到哪里,我发现我的解决方案 Getting the selected value dropdown jstl
希望它为你工作
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
下面是一个简单的例子可以在javascript
首先,我们设计了UI的下拉列表中选择的值下拉
<div class="col-xs-12">
<select class="form-control" id="language">
<option>---SELECT---</option>
<option>JAVA</option>
<option>C</option>
<option>C++</option>
<option>PERL</option>
</select>
接下来我们需要编写脚本来获得所选择的项目
<script type="text/javascript">
$(document).ready(function() {
$('#language').change(function() {
var doc = document.getElementById("language");
alert("You selected " + doc.options[doc.selectedIndex].value);
});
});
现在时更改下拉列表中选择的项目将被警告。
根据Html5规范,你应该使用 - element.options [e.selectedIndex]。 text
例如,如果你有选择框如下图所示:
<select id="selectbox1">
<option value="1">First</option>
<option value="2" selected="selected">Second</option>
<option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>
您可以使用下面的脚本获取值:
<script>
function GetItemValue(q) {
var e = document.getElementById(q);
var selValue = e.options[e.selectedIndex].text ;
alert("Selected Value: "+selValue);
}
</script>
屡试不爽。
你在sv中得到什么? – Kangkan 2012-01-12 09:03:21
您可以粘贴您的html内容以及使用的javascript函数 – AmGates 2012-01-12 09:16:15
另请参阅:http:// stackoverflow。com/questions/1085801/how-to-get-selected-value-dropdownlist -using-javascript – Kangkan 2012-01-12 09:30:14