Home > Web Front-end > JS Tutorial > body text

How to Get Selected Values from a Multiple Select Box in JavaScript?

Barbara Streisand
Release: 2024-11-04 17:00:02
Original
456 people have browsed it

How to Get Selected Values from a Multiple Select Box in JavaScript?

Obtain Values from a Multiple Select Box Using JavaScript

In scenarios where you encounter a multiple select box, accessing its selected values is essential. This question delves into an effective approach to retrieve these values using JavaScript.

To begin with, the code snippet you provided iterates through the options of the multiple select box, checking if each option is selected. If true, the option's value is added to an array.

An alternative solution is presented below, offering a concise and efficient way to obtain the selected values:

<code class="js">function getSelectValues(select) {
  // Create an empty array to store the values.
  const result = [];

  // Obtain the options from the select element.
  const options = select && select.options;

  // Loop through the options to check which ones are selected.
  for (let i = 0; i < options.length; i++) {
    const option = options[i];

    // If the option is selected, we push its value into the result array.
    if (option.selected) {
      result.push(option.value || option.text);
    }
  }

  // Return the populated result array with the selected values.
  return result;
}
Copy after login

This function takes in a select element as an argument and returns an array of selected values. Here's a quick example demonstrating its usage:

<code class="html"><select multiple>
  <option>Option 1</option>
  <option value="value-2">Option 2</option>
</select>

<button onclick="
  const selectElement = document.getElementsByTagName('select')[0];
  const selectedValues = getSelectValues(selectElement);
  console.log(selectedValues);
">Show Selected Values</button></code>
Copy after login

The above is the detailed content of How to Get Selected Values from a Multiple Select Box in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template