如何从中获取所有选定的值?

时间:2023-02-10 23:47:44

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 }.

例如,如果用户选择了午餐和零食,我想要一个{2,4}的数组。

This seems like it should be a very simple task but I can't seem to do it.

这似乎应该是一个非常简单的任务,但我似乎做不到。

Thanks.

谢谢。

9 个解决方案

#1


54  

The usual way:

通常的方法:

var values = $('#select-meal-type').val();

From the docs:

从文档:

In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;

#2


78  

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?:

如何使用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;
}

#3


18  

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);

#4


7  

$('#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());
});

#5


3  

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
})

#6


2  

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>

fiddle

小提琴

#7


2  

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,而不是数组。这个调用将它转换为数组,这样我们就可以应用映射函数,它提取值。

#8


0  

Works everywhere without jquery:

工作都没有jquery:

var getSelectValues = function (select) {
    var ret = [];

    // fast but not universally supported
    if (select.selectedOptions != undefined) {
        for (var i=0; i < select.selectedOptions.length; i++) {
            ret.push(select.selectedOptions[i].value);
        }

    // compatible, but can be painfully slow
    } else {
        for (var i=0; i < select.options.length; i++) {
            if (select.options[i].selected) {
                ret.push(select.options[i].value);
            }
        }
    }
    return ret;
};

#9


0  

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

#1


54  

The usual way:

通常的方法:

var values = $('#select-meal-type').val();

From the docs:

从文档:

In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;

#2


78  

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?:

如何使用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;
}

#3


18  

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);

#4


7  

$('#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());
});

#5


3  

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
})

#6


2  

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>

fiddle

小提琴

#7


2  

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,而不是数组。这个调用将它转换为数组,这样我们就可以应用映射函数,它提取值。

#8


0  

Works everywhere without jquery:

工作都没有jquery:

var getSelectValues = function (select) {
    var ret = [];

    // fast but not universally supported
    if (select.selectedOptions != undefined) {
        for (var i=0; i < select.selectedOptions.length; i++) {
            ret.push(select.selectedOptions[i].value);
        }

    // compatible, but can be painfully slow
    } else {
        for (var i=0; i < select.options.length; i++) {
            if (select.options[i].selected) {
                ret.push(select.options[i].value);
            }
        }
    }
    return ret;
};

#9


0  

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