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>
</select>
</form>
to create the form with the select dropdown.
Then we get the select by writing:
const select = document.querySelector('select')
select.addEventListener('change', () => {
const {
text,
value
} = 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.options[select.selectedIndex]
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.