Logo

How can I get the selected text (not the selected value) from a drop-down list in jQuery?

When you’re working with a drop-down (i.e., a <select> element) and want to retrieve the visible text (not just the underlying value) of the selected option, jQuery offers a clean, concise approach. Here’s how to do it.

1. The Primary Method

var selectedText = $('#mySelect option:selected').text(); console.log(selectedText);
  • #mySelect option:selected: Selects the currently chosen <option> within the <select> element with the ID mySelect.
  • .text(): Extracts the text content of that <option>—which is the label users see.

2. Practical Example

Imagine you have the following HTML:

<select id="mySelect"> <option value="js">JavaScript</option> <option value="py">Python</option> <option value="cpp">C++</option> </select>

By running:

var selectedText = $('#mySelect option:selected').text(); alert('You selected ' + selectedText);

If “Python” is chosen, the alert will display:

You selected Python

3. Change Event for Dynamic Retrieval

Often, you’ll want to update some part of the page whenever a user changes the selection. You can do this by listening for the change event:

$('#mySelect').on('change', function() { var selectedText = $(this).find('option:selected').text(); $('#output').text('Selected: ' + selectedText); });

Assuming you have an element with the ID output, like:

<div id="output"></div>

the chosen text will dynamically appear as soon as the user picks an option.

4. Common Pitfalls to Avoid

  1. Mixing .val() and .text(): .val() is for retrieving the value attribute. If you need the displayed text, stick to .text().
  2. Forgetting option:selected: Using $('#mySelect').text() alone will give you the entire text content of the <select> plus all its options, which isn’t what you want.
  3. Not Handling Multiple Selections: If your <select> element supports multiple options (using multiple), you need to handle each selected option individually.

Level Up Your JavaScript Skills

If you’re looking to master the fundamentals of JavaScript and become a front-end wizard, consider taking:

Go Beyond: Practice with Mock Interviews

Nothing beats firsthand experience. Check out the Coding Mock Interview at DesignGurus.io, where ex-FAANG engineers guide you through real-world interview scenarios, offering feedback and insights that level up your interviewing game.

Final Thoughts
Using jQuery’s .text() on the option:selected is the quickest way to grab that user-visible text. This straightforward method keeps your code clean, helps ensure user feedback is both timely and accurate, and pairs beautifully with dynamic UI updates. Happy coding!

CONTRIBUTOR
TechGrind