且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 JavaScript 获取下拉列表中的选定值

更新时间:2022-11-10 19:27:08

如果你有一个看起来像这样的 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