Javascript 如何从 <select multiple=multiple> 中获取所有选定的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11821261/
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 from <select multiple=multiple>?
提问by Kyle
Seemed odd I couldn't find this one already asked, but here it goes!
似乎很奇怪,我找不到已经问过的人,但它来了!
I have an html as follows:
我有一个 html 如下:
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option value="3">Dinner</option>
<option value="4">Snacks</option>
<option value="5">Dessert</option>
</select>
How do I get all the values(an array?) that the user has selected in javascript?
如何获取用户在 javascript 中选择的所有值(数组?)?
For example, if the user has selected Lunch and Snacks, I want an array of { 2, 4 }.
例如,如果用户选择了 Lunch 和 Snacks,我想要一个 { 2, 4 } 的数组。
This seems like it should be a very simple task but I can't seem to do it.
这似乎应该是一项非常简单的任务,但我似乎无法做到。
Thanks.
谢谢。
采纳答案by Felix Kling
回答by lvoelk
Unless a question asks for JQuery the question should be first answered in standard javascript as many people do not use JQuery in their sites.
除非问题要求使用 JQuery,否则应该首先用标准 javascript 回答问题,因为许多人不在他们的站点中使用 JQuery。
From RobG How to get all selected values of a multiple select box using JavaScript?:
来自 RobG如何使用 JavaScript 获取多选框的所有选定值?:
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;
}
回答by KyleFarris
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
实际上,我发现使用纯 JavaScript 的最佳、最简洁、最快和最兼容的方式(假设您不需要完全支持 IE lte 8)如下:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
更新(2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
一种更简洁的使用 ES6/ES2015 的方式(对于支持它的浏览器):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
回答by Tomá? Zato - Reinstate Monica
If you wanna go the modern way, you can do this:
如果你想走现代之路,你可以这样做:
const selectedOpts = [...field.options].filter((x) => x.selected);
The ...
operator maps iterable (HTMLOptionsCollection
) to the array.
的...
操作者可迭代映射(HTMLOptionsCollection
)到阵列。
If you're just interested in the values, you can add a map()
call:
如果您只对这些值感兴趣,可以添加一个map()
调用:
const selectedValues = [...field.options]
.filter((x) => x.selected)
.map((x)=>x.value);
回答by Hassan
First, use Array.from
to convert the HTMLCollection
object to an array.
首先,使用Array.from
将HTMLCollection
对象转换为数组。
let selectElement = document.getElementById('categorySelect')
let selectedValues = Array.from(selectElement.selectedOptions)
.map(option => option.value) // make sure you know what '.map' does
// you could also do: selectElement.options
回答by John Conde
$('#select-meal-type :selected')
will contain an array of all of the selected items.
$('#select-meal-type :selected')
将包含所有选定项目的数组。
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
?
?
回答by undefined
Try this:
尝试这个:
$('#select-meal-type').change(function(){
var arr = $(this).val()
});
Demo
演示
$('#select-meal-type').change(function(){
var arr = $(this).val();
console.log(arr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option value="3">Dinner</option>
<option value="4">Snacks</option>
<option value="5">Dessert</option>
</select>
回答by Fergie
Update October 2019
2019 年 10 月更新
The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.
以下应该在所有现代浏览器上“独立”工作,没有任何依赖或转译。
<!-- display a pop-up with the selected values from the <select> element -->
<script>
const showSelectedOptions = options => alert(
[...options].filter(o => o.selected).map(o => o.value)
)
</script>
<select multiple onchange="showSelectedOptions(this.options)">
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
回答by ewroman
if you want as you expressed with breaks after each value;
如果你想在每个值后用中断表示;
$('#select-meal-type').change(function(){
var meals = $(this).val();
var selectedmeals = meals.join(", "); // there is a break after comma
alert (selectedmeals); // just for testing what will be printed
})
回答by adlr0
If you need to respond to changes, you can try this:
如果您需要响应更改,可以尝试以下操作:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions)
is needed because e.target.selectedOptions
returns a HTMLCollection
, not an Array
. That call converts it to Array
so that we can then apply the map
function, which extract the values.
该[].slice.call(e.target.selectedOptions)
是必要的,因为e.target.selectedOptions
回报HTMLCollection
,而不是一个Array
。该调用将其转换为 ,Array
以便我们可以应用map
提取值的函数。