从 JavaScript 的下拉列表中获取多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10241759/
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-24 00:27:48  来源:igfitidea点击:

get multiple values from dropdownlist in JavaScript

javascripthtmldomhtml-select

提问by milind

How can I get the values selected in the drop-down list, using a JavaScript function? User can select multiple values from both the elements. Following are the elements I'm using. Thanks in advance.

如何使用 JavaScript 函数获取下拉列表中选择的值?用户可以从这两个元素中选择多个值。以下是我正在使用的元素。提前致谢。

<select name="icOptions" id="icOptions" style="display: none" multiple="multiple">
  <option value="Choose an Option" selected="selected">Choose a Team </option>
  <option value="IDX">IDX</option>
  <option value="Support">SUPPORT</option>
  <option value="webapps">WEBAPPS</option>
</select>

<select name="ocOptions" id="ocOptions" style="display: none" multiple="multiple">
  <option value="Choose an Option" selected="selected">Choose a TeamMember </option>
  <option value="sanjay740">sanjay740</option>
  <option value="milind740">milind740</option>
</select>

回答by Gwyn Howell

var fld = document.getElementById('icOptions');
var values = [];
for (var i = 0; i < fld.options.length; i++) {
  if (fld.options[i].selected) {
    values.push(fld.options[i].value);
  }
}
// do something with values

回答by Tamil

Really Awesome Library for your need using jQuery or Prototype http://harvesthq.github.com/chosen/Have a look at it.

使用 jQuery 或 Prototype http://harvesthq.github.com/chosen/满足您需要的真正很棒的库 看看它。

It supports select & multiselect in a really nice way

它以一种非常好的方式支持选择和多选

回答by Dominic

An ES6/functional style alternative to the accepted answer:

已接受答案的 ES6/函数式替代方案:

const values = Array.apply(null, e.target.options)
  .filter(option => option.selected)
  .map(option => option.value);