To retrieve the selected text from a dropdown list (<select>
element) using jQuery, follow these steps:
1. Basic Syntax
Use the :selected
selector to target the chosen option and extract its text content with .text()
:
// Get the text of the selected option
const selectedText = $('#selectBoxId option:selected').text();
2. Example: Get Text on Button Click
HTML:
<select id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
<button id="getTextBtn">Show Selected Text</button>
jQuery:
$('#getTextBtn').click(function() {
const selectedText = $('#fruits option:selected').text();
alert(selectedText); // e.g., "Banana"
});
3. Example: Get Text on Selection Change
$('#fruits').change(function() {
const selectedText = $(this).find('option:selected').text();
console.log(selectedText); // Updates when the selection changes
});
Key Notes
.text()
vs.val()
:.text()
→ Returns the display text (e.g., “Apple”)..val()
→ Returns thevalue
attribute of the option (e.g., “apple”).- Dynamic Elements: For dynamically generated
<select>
elements, use event delegation:
$(document).on('change', '#dynamicSelect', function() {
const text = $(this).find('option:selected').text();
});
Edge Cases
- No Selection: If no option is selected (e.g., in a multi-select), check for existence:
const $selectedOption = $('#selectBoxId option:selected');
if ($selectedOption.length) {
const text = $selectedOption.text();
}
- Placeholder Options: Handle placeholder text (e.g.,
<option disabled selected>Choose...</option>
).
Full Example
<select id="countries">
<option value="" disabled selected>Select a country</option>
<option value="us">United States</option>
<option value="ca">Canada</option>
</select>
<p id="result"></p>
$('#countries').change(function() {
const selectedText = $(this).find('option:selected').text();
$('#result').text(`Selected: ${selectedText}`);
});
Summary
Method | Use Case |
---|---|
$('#selectId option:selected').text() | Directly retrieve selected text |
$(this).find('option:selected').text() | Inside event handlers |
This approach ensures you always get the human-readable text of the selected option.