Explain Codes LogoExplain Codes Logo

Get selected option text with JavaScript

javascript
event-listeners
dom-manipulation
functions
Alex KataevbyAlex Kataev·Nov 21, 2024
TLDR

Here's a quick and simple way to retrieve the visible text of the selected option in a <select> dropdown using JavaScript:

var selectedText = document.querySelector('#mySelect').selectedOptions[0].text;

The variable selectedText stores the display text from the selected option in a dropdown with the ID mySelect.

Real-time text retrieval on selection changes

For dynamic behavior, hook up the change event to the <select> element. This will let you fetch and trigger actions every time the user switches selection:

document.getElementById('mySelect').addEventListener('change', function() { // Who needs a fortune cookie when the browser's got your back! 🥠🦾 alert(this.options[this.selectedIndex].text); });

Get selected text using value attribute

Occasionally, the value attribute might be identical to the option text. Simplify text retrieval in those cases:

var selectedText = document.querySelector('#mySelect').value;

Caution, this works only when display text and value are equal, which isn't always true.

Improve UX with clear labels

To differentiate dropdowns, especially in forms, use label elements:

<label for="mySelect">Your Destiny:</label> <select id="mySelect"> <!-- options, options, options... --> </select>

With distinct labels, end-users enjoy a smoother experience and you can reference the dropdowns conveniently in your code.

Reusable function for multiple dropdowns

Dealing with a horde of dropdowns? Fear not! A single, reusable function will ease your pain:

function getSelectedText(elementId) { // Unleash the power of… drop-down-omancy! 🔮 let dropdown = document.getElementById(elementId); return dropdown.options[dropdown.selectedIndex].text; } // Call the magic function as you please var chosenText1 = getSelectedText('dropdown1'); var chosenText2 = getSelectedText('dropdown2');