How to get all selected option text form multi-select using JavaScript?

Sometimes, we want to get all selected option text form multi-select using JavaScript.

In this article, we’ll look at how to get all selected option text form multi-select using JavaScript.

How to get all selected option text form multi-select using JavaScript?

To get all selected option text form multi-select using JavaScript, we can select all the selected options with the checked pseudoselector.

And then we can get the value from them.

For instance, we write:

<select multiple>
  <option>apple</option>
  <option>orange</option>
  <option>grape</option>
  <option>pear</option>
  <option>banana</option>
</select>

to add a multiselect.

Then we write:

const select = document.querySelector('select')
select.onchange = (e) => {
  const selected = [...document.querySelectorAll('select option:checked')]
    .map(item => item.value)
    .join()
  console.log(selected)
}

We get the select element with the document.querySelector.

Then we set the onchange property to a function that gets all the selected options and map them to an array with [...document.querySelectorAll('select option:checked')].

Then we map the value of the array to an array of the selected option element values.

Finally, we call join to join them together.

Conclusion

To get all selected option text form multi-select using JavaScript, we can select all the selected options with the checked pseudoselector.

And then we can get the value from them.