Html select multiple get all values at onchange event

血红的双手。 提交于 2019-12-10 14:25:50

问题


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>

回答1:


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>



回答2:


You can use jquery to solve it:

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


来源:https://stackoverflow.com/questions/30372235/html-select-multiple-get-all-values-at-onchange-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!