Sometimes, we want to get selected option text with JavaScript.
In this article, we’ll look at how to get selected option text with JavaScript.
How to get selected option text with JavaScript?
To get selected option text with JavaScript, we use the selectedOptions
property.
For instance, we write
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
to add a select drop down.
Then we write
const areaSelect = document.querySelector(`#box1`);
areaSelect.addEventListener(`change`, (e) => {
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
});
to select the drop down with querySelector
.
Then we listen to the change event emitted by it.
We get the selected option’s text with select.selectedOptions[0].text
Conclusion
To get selected option text with JavaScript, we use the selectedOptions
property.