在 Javascript 中的多选标记中获取选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11583728/
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
Getting the selected values in a multiselect tag in Javascript
提问by aurora
I have the following code
我有以下代码
function searchFlights() {
var select1 = document.getElementById("airports-select-1");
var selected1 = [];
while(select1.selectedIndex != -1) {
if(select1.selectedIndex != 0) selected1.push(select1.options[select1.selectedIndex].value);
select1.options[select1.selectedIndex].selected = false;
}
console.log(selected1);
}
This works right, but as you can see from the code this line:
这工作正常,但正如您从代码中看到的这一行:
select1.options[select1.selectedIndex].selected = false;
Is doing a deselecting of the value.
正在取消选择该值。
Now, I do not want to deselect the values. If I uncomment that line in the code, the code will run forever.
现在,我不想取消选择这些值。如果我在代码中取消注释该行,代码将永远运行。
Is there any more refined and sophisticated solution for retrieving multiple values from a select tag using Javascript?
是否有更精细和复杂的解决方案来使用 Javascript 从选择标签中检索多个值?
回答by j08691
Wouldn't this do it:
这不是这样做的吗:
function searchFlights() {
var select1 = document.getElementById("airports-select-1");
var selected1 = [];
for (var i = 0; i < select1.length; i++) {
if (select1.options[i].selected) selected1.push(select1.options[i].value);
}
console.log(selected1);
}?
function searchFlights() {
var select1 = document.getElementById("airports-select-1");
var selected1 = [];
for (var i = 0; i < select1.length; i++) {
if (select1.options[i].selected) selected1.push(select1.options[i].value);
}
console.log(selected1);
}
<form method="post">
<select name="Select1" multiple="multiple" size="8" id="airports-select-1" onblur="searchFlights()" ;>
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
<option>ddd</option>
<option>eee</option>
</select>
</form>
回答by Adam Leggett
Update for 2018:
2018 年更新:
If the
<select>
element contains aselectedOptions
property, use that collection. The only browser still in wide circulation that doesn't support this is IE (any version). Edge does support it.If this is not supported, the answer by @j08691 is still correct, but as a performance optimization you can start iterating options at
selectedIndex
instead of0
. This is the index of the first selected option, or-1
if nothing is selected.
如果
<select>
元素包含selectedOptions
属性,请使用该集合。唯一不支持此功能的仍在广泛流通的浏览器是 IE(任何版本)。Edge确实支持它。如果这不受支持,@j08691 的答案仍然是正确的,但作为性能优化,您可以开始迭代选项
selectedIndex
而不是0
。这是第一个选定选项的索引,或者-1
如果没有选择任何选项。
回答by Ray Toal
Another approach for those who like a more functional style:
对于喜欢更实用风格的人的另一种方法:
selections = Array.from(selectBox.options).filter(o => o.selected).map(o => o.value)
or
或者
selections = Array.from(selectBox.selectedOptions).map(o => o.value)