JavaScript Answers

How to Get an Option’s Text or Value with JavaScript?

Spread the love

To get an option’s text or value with JavaScript, we can use properties built into the browser to get the options’ text or value.

For instance, we can write:

<form name="foodSelect">
  <select name="mainCourse">
    <option>- select -</option>
    <option value="breakfast">Breakfast</option>
    <option value="lunch">Lunch</option>
    <option value="dinner">Dinner</option>

to create the form with the select dropdown.

Then we get the select by writing:

const select = document.querySelector('select')

select.addEventListener('change', () => {
  const {
  } = select.options[select.selectedIndex]
  console.log(text, value)

We get the select element with document.querySelector .

Then we get the option element that’s selected with:


select.selectedIndex has the index of the element that’s selected.

The text property has the text of the option element that’s displayed to the user.

value has the value of the value attribute of the selected option.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *