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

<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>


当前回答

var strUser = e.options[e.selectedIndex].value;

这是正确的,应该为您提供值。是你想要的文本吗?

var strUser = e.options[e.selectedIndex].text;

所以你对术语很清楚:

<select>
    <option value="hello">Hello World</option>
</select>

此选项具有:

索引=0值=hello文本=你好世界

其他回答

运行示例:

var e=document.getElementById(“ddlViewBy”);var val1=e.options[e.selectedIndex].value;var txt=e.options[e.selectedIndex].text;document.write(“<br/>所选选项值:”+val1);document.write(“<br/>所选选项文本:”+txt);<select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”>test2</option><option value=“3”selected=“selected”>test3</option></选择>

注意:下拉列表更改时,值不会更改,如果您需要该功能,则需要执行onClick更改。

对于如何实现这一点,我有一点不同的看法。我通常使用以下方法(这是一种更简单的方法,而且据我所知,它适用于所有浏览器):

<select onChange="functionToCall(this.value);" id="ddlViewBy">
  <option value="value1">Text one</option>
  <option value="value2">Text two</option>
  <option value="value3">Text three</option>
  <option value="valueN">Text N</option>
</select>

纯JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option

角度JS:(http://jsfiddle.net/qk5wwyct):

// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// JavaScript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'
}];

另一种解决方案是:

document.getElementById('elementId').selectedOptions[0].value

制作一个包含多个选项的下拉菜单(根据需要选择多个!)

<select>
  <option value="giveItAName">Give it a name
  <option value="bananaShark">Ridiculous animal
  <ooption value="Unknown">Give more options!
</select>

我把它弄得有点滑稽。

下面是代码段:

<选择><option value=“RidicousObject”>香蕉鲨<option value=“SuperDuperCoding”>选择标记和选项标记!<option value=“未知”>添加更多标签以添加更多选项!</选择><h1>仅1个选项(无用)</h1><选择><option value=“Single”>单一选项</选择>

是的,片段奏效了。