Home  >  Article  >  Web Front-end  >  How to Efficiently Retrieve Selected Values from a Multi-Select Element in JavaScript?

How to Efficiently Retrieve Selected Values from a Multi-Select Element in JavaScript?

DDD
DDDOriginal
2024-11-04 06:24:021040browse

How to Efficiently Retrieve Selected Values from a Multi-Select Element in JavaScript?

How to Retrieve Selected Values from a Multi-Select Element

In your scenario, you have a element. Here's a modified version of your code that leverages this function:

<code class="javascript">function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i = 0, iLen = options.length; i < iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}</code>

To use this function, simply pass the