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

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

How to get all selected values of a multiple select box?

javascripthtmldrop-down-menu

提问by Tijo K Varghese

I have a <select>element with the multipleattribute. 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;
});

CLICK HERE TO SEE THE DEMO

单击此处查看演示

回答by Rick Viscomi

ES6

ES6

[...select.options].filter(option => option.selected).map(option => option.value)

Where selectis 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 using Array.from())
  • filter(...)reduces the options to only the ones that are selected
  • map(...)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,

详细,

  • selectedOptionsreturns a list of selected items.
  • Specifically, it returns a read-only HTMLCollectioncontaining HTMLOptionElements.
  • ...is spread syntax. It expands the HTMLCollection's elements.
  • [...]creates a mutable Arrayobject from these elements, giving you an array of HTMLOptionElements.
  • map()replaces each HTMLObjectElementin the array (here called option) with its value(option.value).
  • selectedOptions返回所选项目的列表。
  • 具体而言,它返回一个只读的HTMLCollection含有HTMLOptionElements
  • ...传播语法。它扩展了HTMLCollection的元素。
  • [...]Array从这些元素创建一个可变对象,为您提供一个HTMLOptionElements.
  • map()用其( )替换HTMLObjectElement数组中的每个(此处称为)。optionoption.value

Dense, but it seems to work.

密集,但它似乎工作。

Watch out, selectedOptionsisn'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 [].reducefor 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;
  }, []);
};