user3065901
user3065901

Reputation: 4778

Html select multiple get all values at onchange event

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>

Upvotes: 15

Views: 43100

Answers (4)

dessalines
dessalines

Reputation: 7352

An ES6 answer:

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

let selected = options
.filter(o => o.selected)
.map(o => o.value);

Upvotes: 1

Jeremy
Jeremy

Reputation: 41

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);
});

Upvotes: 2

Thomas Theunen
Thomas Theunen

Reputation: 1274

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>

Upvotes: 24

PhuLuong
PhuLuong

Reputation: 537

You can use jquery to solve it:

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

Upvotes: 5

Related Questions