Javascript 使用 JS 从列表中获取所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2296971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:39:47  来源:igfitidea点击:

Get selected Item from the list with JS

javascript

提问by Alex

I have an html list with some items loaded. I am able to get the select list object using the following code:

我有一个 html 列表,其中加载了一些项目。我可以使用以下代码获取选择列表对象:

var list = document.getElementById('ddlReason');

but I need help with figuring out how to detect which value has been chosen from the list.

但我需要帮助弄清楚如何检测从列表中选择了哪个值。

回答by Erik

// Gets your select
var list = document.getElementById('ddlReason');

// Get the index of selected item, first item 0, second item 1 etc ...
var INDEX = list.selectedIndex;

// Viola you're done
alert(list[INDEX].value);

Edit (forgot .value).

编辑(忘记 .value)。

You can also make that a bit more concise, but I wanted to make it readable so you could see what was going on. Shorter version:

你也可以让它更简洁一点,但我想让它可读,这样你就可以看到发生了什么。较短的版本:

var list = document.getElementById('ddlReason');
alert(list[list.selectedIndex].value);

回答by user3381402

Actually you can do this

其实你可以这样做

var list = document.getElementById('ddlReason').value;

and if you make an alert to list, you'll get the value of your select tag.

如果您向 发出警报list,您将获得 select 标签的值。

回答by Scott Saunders

The list object will have a 'options' attribute that is an array of all the options in the list and a 'selectedIndex' attribute that contains the index of the selected item (or the first selected item if there are multiple). So you can do this:

列表对象将有一个 'options' 属性,它是列表中所有选项的数组,以及一个 'selectedIndex' 属性,它包含所选项目的索引(如果有多个,则为第一个所选项目)。所以你可以这样做:

var list = document.getElementById('ddlReason');
var selectedValue = list.options[list.selectedIndex];