且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Html select multiple获取onchange事件的所有值

更新时间:2023-10-17 19:49:40



function getSelectedOptions(sel){var opts = [],opt; var len = sel.options.length; for(var i = 0; i< len; i ++){opt = sel.options [i];如果(opt.selected){opts.push(opt);警报(opt.value); }} return opts;} p> < select name = myarray []id =myarrayclass =select2-select reqstyle =width:90%; onChange =getSelectedOptions(this)multiple> < option value =1> 1< / option> < option value =2> 2< / option> < option value =3> 3< / option>< / select>

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>

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>