skip to Main Content

I have a select element on my web page that allows the user to select multiple options. I want to obtain an array with the values ​​of all the options that are currently selected.

I have tried using the selectedOptions property of the select element, but it only gives me the first selected option.

2

Answers


  1. The selectedOptions property of the select element should give you a list of all the currently selected options, not just the first one.

    This property returns an HTMLCollection of option elements that are currently selected in the select element.

    Here’s an example of how you can use it to get an array of the values of all selected options:

    let selectElement = document.getElementById("your-select-element-id");
    let selectedOptions = Array.from(selectElement.selectedOptions);
    let selectedValues = selectedOptions.map(option => option.value);
    

    document.getElementById("your-select-element-id") gets the select element with the specified ID. Use querySelector() or whatever you like instead of getElementById().

    Array.from(selectElement.selectedOptions) converts the HTMLCollection of selected options into an array.

    selectedOptions.map(option => option.value) creates a new array with the values of all selected options.

    Login or Signup to reply.
  2.   <body>
        <select
          multiple
          id="ss"
        >
          <option value="a" selected>American Black Bear</option>
          <option value="b" selected>Asiatic Black Bear</option>
          <option value="c">Brown Bear</option>
        </select>
        <script>
          console.log(
            Array.from(document.querySelectorAll("#select > option[selected]")).map(
              (e) => e.getAttribute("value")
            )
          );
        </script>
      </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search