Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-04 06:24:02
Original
1076 people have browsed it

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>
Copy after login

To use this function, simply pass the