Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 278
user3065901 Avatar asked May 21 '15 11:05

user3065901


People also ask

How do you select multiple values in HTML?

When present, it specifies that multiple options can be selected at once. Selecting multiple options vary in different operating systems and browsers: For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

Can I use Onchange in select tag?

Yes. Add an onChange property to the first select, then use it to call a javascript function you have written elsewhere.

How can we select multiple values from dropdown?

To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.


1 Answers

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>
like image 91
Thomas Theunen Avatar answered Oct 03 '22 21:10

Thomas Theunen