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

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


当前回答

有两种方法可以使用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'

其他回答

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

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

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

所以你对术语很清楚:

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

此选项具有:

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

在onchange函数中有一个简单的方法:

event.target.options[event.targets.selectedIndex].dataset-name

我不知道我是不是那个没有正确回答问题的人,但这对我很有用:

例如,在HTML中使用onchange()事件。

<select id="numberToSelect" onchange="selectNum()">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

JavaScript

function selectNum() {
    var strUser = document.getElementById("numberToSelect").value;
}

这将为您提供每次单击时选择下拉列表中的任何值。

在更现代的浏览器中,querySelector允许我们使用:checked伪类在一条语句中检索所选选项。从所选选项中,我们可以收集所需的任何信息:

const opt=document.querySelector(“#ddlViewBy选项:选中”);//opt现在是选定的选项,因此console.log(opt.value,'是所选值');console.log(opt.text,“是所选选项的文本”);<select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择>

Use:

<select id="Ultra" onchange="alert(this.value)">
    <option value="0">Select</option>
    <option value="8">text1</option>
    <option value="5">text2</option>
    <option value="4">text3</option>
</select>

从元素内部访问任何输入/表单字段时,都可以使用“this”关键字。这样就不需要在DOM树中查找表单,然后在表单中查找该元素。