Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript在下拉列表中获取选定的值(Get selected value in dropdown list using JavaScript)

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

(如何使用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;
  ask by Fire Hand translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a select element that looks like this:

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

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

Running this code:

(运行此代码:)

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

Would make strUser be 2 .

(将strUser设为2 。)

If what you actually want is test2 , then do this:

(如果您真正想要的是test2 ,请执行以下操作:)

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

Which would make strUser be test2

(这会使strUser成为test2)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...