Html select multiple get all values at onchange event
Asked Answered
D

4

15

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.

Is it possible to get all the elements selected as array at 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>
Divinadivination answered 21/5, 2015 at 11:20 Comment(4)
are you using jQuery? or just plain javascriptMcquillin
You can have a look here: #5866669Insurgence
It’s possible to use myarray.selectedOptions.Desrochers
Does this answer your question? How to get all selected values of a multiple select box?Reactionary
I
24

This example might help without 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>
Insurgence answered 21/5, 2015 at 11:33 Comment(0)
A
5

You can use jquery to solve it:

get_values=function(){
    var retval = [];    
    $("#myarray:selected").each(function(){
        retval .push($(this).val()); 
    });
    return retval;
};
Aishaaisle answered 21/5, 2015 at 11:26 Comment(0)
A
2

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

<select id="my-array" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
const myArray = document.getElementById('my-array');
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);
});
Ancheta answered 26/5, 2020 at 8:59 Comment(0)
A
1

An ES6 answer:

let options: HTMLOptionElement[] = Array.from(event.target.options);

let selected = options
.filter(o => o.selected)
.map(o => o.value);
Androus answered 7/9, 2022 at 15:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.