Javascript 如何获取多选框的所有选定值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5866169/
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
How to get all selected values of a multiple select box?
提问by Tijo K Varghese
I have a <select>
element with the multiple
attribute. How can I get this element's selected values using JavaScript?
我有一个<select>
具有该multiple
属性的元素。如何使用 JavaScript 获取此元素的选定值?
Here's what I'm trying:
这是我正在尝试的:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
回答by RobG
No jQuery:
没有jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
快速示例:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
回答by Sukhjeevan
Check-it Out:
一探究竟:
HTML:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
查询:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
回答by Rick Viscomi
ES6
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select
is a reference to the <select>
element.
哪里select
是对<select>
元素的引用。
To break it down:
分解:
[...select.options]
takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider usingArray.from()
)filter(...)
reduces the options to only the ones that are selectedmap(...)
converts the raw<option>
elements into their respective values
[...select.options]
获取类似 Array 的选项列表并对其进行解构,以便我们可以在其上使用 Array.prototype 方法(编辑:也考虑使用Array.from()
)filter(...)
将选项减少到仅选定的选项map(...)
将原始<option>
元素转换为它们各自的值
回答by uKolka
Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:
与已经建议的几乎相同,但有点不同。与Vanilla JS 中的jQuery 代码一样多:
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
It seems to be fasterthan a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.
它似乎比 IE、FF 和 Safari 中的循环更快。我觉得有趣的是它在 Chrome 和 Opera 中更慢。
Another approach would be using selectors:
另一种方法是使用选择器:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);
回答by KAFFEECKO
suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:
假设 multiSelect 是 Multiple-Select-Element,只需使用它的 selectedOptions 属性:
//show all selected options in the console:
for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
console.log( multiSelect.selectedOptions[i].value);
}
回答by To_wave
Here is an ES6implementation:
这是一个ES6实现:
value = Array(...el.options).reduce((acc, option) => {
if (option.selected === true) {
acc.push(option.value);
}
return acc;
}, []);
回答by Kevin W Matthews
Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptionsproperty:
基于Rick Viscomi的回答,尝试使用 HTML 选择元素的selectedOptions属性:
let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);
In detail,
详细,
selectedOptions
returns a list of selected items.- Specifically, it returns a read-only HTMLCollectioncontaining HTMLOptionElements.
...
is spread syntax. It expands theHTMLCollection
's elements.[...]
creates a mutableArray
object from these elements, giving you an array ofHTMLOptionElements
.map()
replaces eachHTMLObjectElement
in the array (here calledoption
) with its value(option.value
).
selectedOptions
返回所选项目的列表。- 具体而言,它返回一个只读的HTMLCollection含有HTMLOptionElements。
...
是传播语法。它扩展了HTMLCollection
的元素。[...]
Array
从这些元素创建一个可变对象,为您提供一个HTMLOptionElements
.map()
用其值( )替换HTMLObjectElement
数组中的每个(此处称为)。option
option.value
Dense, but it seems to work.
密集,但它似乎工作。
Watch out, selectedOptions
isn't supportedby IE!
注意,IEselectedOptions
不支持!
回答by Krish K
Check this:
检查这个:
HTML:
HTML:
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
Javascript one line code
Javascript 一行代码
Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);
回答by Pankaj Chauhan
You Can try this script
你可以试试这个脚本
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
回答by rouan
You can use [].reduce
for a more compact implementation of RobG's approach:
您可以使用[].reduce
更紧凑的RobG 方法实现:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};