使用JavaScript在下拉列表中获取选定的值 [英] Get selected value in dropdown list using JavaScript

查看:78
本文介绍了使用JavaScript在下拉列表中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JavaScript从下拉列表中获取选定的值?

How do I get the selected value from a dropdown list using JavaScript?

我尝试了以下方法,但是它们都返回选择的索引而不是值:

I tried the methods below, but they all return the selected index instead of the value:

var as = document.form1.ddlViewBy.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

推荐答案

如果您具有如下所示的select元素:

If you have a select element that looks like this:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

运行此代码:

var e = document.getElementById("ddlViewBy");
var strUser = e.value;

strUser设为2.如果您真正想要的是test2,请执行以下操作:

Would make strUser be 2. If what you actually want is test2, then do this:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;

哪个会使strUser成为test2

这篇关于使用JavaScript在下拉列表中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆