如何获取多选框的所有选定值?

Tij*_*ese 69 html javascript drop-down-menu

我有一个属性<select>元素multiple.如何使用JavaScript获取此元素的选定值?

这是我正在尝试的:

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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obG 95

没有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;
}
Run Code Online (Sandbox Code Playgroud)

快速举例:

<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>
Run Code Online (Sandbox Code Playgroud)

  • `select`不是JavaScript中最好的变量名. (12认同)
  • @TecBrat`var options = select && select.options`确保select在访问其属性之前未定义. (4认同)
  • 谢谢你的回答。您能帮我一步步完成吗?我想我明白其中大部分内容,但是 `var options = select &amp;&amp; select.options;` 是做什么的?以我的**缺乏经验**,我期望是“var options = select.options;” (2认同)

Suk*_*van 27

看看这个:

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>
Run Code Online (Sandbox Code Playgroud)

JQUERY:

$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});
Run Code Online (Sandbox Code Playgroud)

点击这里查看演示

  • 不喜欢 - “HTML”不是 HTML(可读,但不是 HTML),答案需要添加 JQuery 作为依赖项。 (3认同)

Ric*_*omi 26

ES6

[...select.options].filter(option => option.selected).map(option => option.value)
Run Code Online (Sandbox Code Playgroud)

哪个select<select>元素的引用.

要打破它:

  • [...select.options]获取类似Array的选项列表并对其进行解构,以便我们可以在其上使用Array.prototype方法(编辑:也考虑使用Array.from())
  • filter(...) 将选项缩小为仅选定的选项
  • map(...)将原始<option>元素转换为各自的值

  • 不错的功能实现:) (3认同)
  • @Evgeny 有很多方法可以解决它。您应该在新答案中发布您的方法。 (2认同)
  • @Anentropic,这是一个很好的问题,但我认为效率并不重要,除非我们谈论数百或数千种选择。 (2认同)

uKo*_*lka 10

与已经提出的相同,但有点不同.与Vanilla JS中的 jQuery一样多的代码:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);
Run Code Online (Sandbox Code Playgroud)

似乎比IE,FF和Safari中的循环更快.我觉得有趣的是它在Chrome和Opera中速度较慢.

另一种方法是使用选择器:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);
Run Code Online (Sandbox Code Playgroud)


小智 9

假设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);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

检查一下:

HTML:

<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
Run Code Online (Sandbox Code Playgroud)

JavaScript 一行代码

Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);
Run Code Online (Sandbox Code Playgroud)