Javascript Html select multiple 在 onchange 事件中获取所有值

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

Html select multiple get all values at onchange event

javascripthtmlselectonchangemulti-select

提问by user3065901

I have a form with a select multiple. I want to get all selected values at onchange event but i dont know if this is possible. I think "this.value" only returns the last element selected.

我有一个选择多个的表格。我想在 onchange 事件中获得所有选定的值,但我不知道这是否可能。我认为“this.value”只返回选择的最后一个元素。

Is it possible to get all the elements selected as array at onchange??

是否可以在 onchange 时将所有元素选为数组?

Thanks in advance.

提前致谢。

<select name="myarray[]" id="myarray" class="select2-select req" style="width: 90%;" onChange="get_values(this.value)" multiple>
    {foreach key=key item=value from=$myarray}
         <option value="{$key}" >{$value}</option>
    {/foreach}
</select>

回答by Thomas Theunen

This example might help without jQuery:

这个例子可能会在没有 jQuery 的情况下有所帮助:

function getSelectedOptions(sel) {
  var opts = [],
    opt;
  var len = sel.options.length;
  for (var i = 0; i < len; i++) {
    opt = sel.options[i];

    if (opt.selected) {
      opts.push(opt);
      alert(opt.value);
    }
  }

  return opts;
}
<select name="myarray[]" id="myarray" class="select2-select req" style="width: 90%;" onChange="getSelectedOptions(this)" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

回答by PhuLuong

You can use jquery to solve it:

您可以使用jquery来解决它:

get_values=function(){
    var retval = [];    
    $("#myarray:selected").each(function(){
        retval .push($(this).val()); 
    });
    return retval;
};

回答by Jeremy

In the example below, i'm builiding arrays of selected options and selected values :

在下面的示例中,我正在构建选定选项和选定值的数组:

<select id="myarray" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
const myarray = document.getElementById('myarray');
myarray.addEventListener('change', (e) => {

  const options = e.target.options;
  const selectedOptions = [];
  const selectedValues = [];

  for (let i = 0; i < options.length; i++) {
    if (options[i].selected) {
      selectedOptions.push(options[i]);
      selectedValues.push(options[i].value);
    }
  }

  console.log(selectedOptions);
  console.log(selectedValues);
});