如何使用JavaScript从下拉列表中获取所选值?
<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>
如何使用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文本=你好世界
其他回答
按照前面的回答,这是我作为一个单线图的方式。这用于获取所选选项的实际文本。已经有一些很好的例子可以获取索引编号。(对于文本,我只是想展示一下)
let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
在一些罕见的情况下,您可能需要使用括号,但这非常罕见。
let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
我怀疑这个过程比双线版本更快。我只是想尽可能地整合我的代码。
不幸的是,这仍然会获取两次元素,这并不理想。一个只抓取一次元素的方法会更有用,但我还没有弄清楚,关于用一行代码来实现这一点。
有两种方法可以使用JavaScript或jQuery完成此操作。
JavaScript:
var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;
alert (getValue); // This will output the value selected.
OR
var ddlViewBy = document.getElementById('ddlViewBy');
var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;
var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;
alert (value); // This will output the value selected
alert (text); // This will output the text of the value selected
jQuery:
$("#ddlViewBy:selected").text(); // Text of the selected value
$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
只需执行:document.getElementById('dselect').options.selectedIndex
然后,您将获得从0开始的select索引值。
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 selectedValue = document.getElementById("ddlViewBy").value;