jQuery Get Text of Selected Option

When working with dropdown menus in web development, you’ll often need to retrieve the text content of the selected option rather than just its value.

This comprehensive guide will show you exactly how to get the text of a selected option using jQuery, with practical examples and best practices.

Understand Select Elements and Their Values

Before getting into the jQuery methods, it’s important to understand that selected elements have two key properties:

  1. Value: The data sent to the server (stored in the value attribute)
  2. Text: The visible text displayed to users (between the opening and closing option tags)

Consider this HTML select element:

<select id="titleSelect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
</select>

If a user selects “Mr”, the value would be “1”, but the text would be “Mr”. Often, you need to access the text content for display purposes or user feedback.

Method 1: Use the :selected Selector (Most Common)

The most popular and easy method to get the selected option text is using jQuery’s :selected selector combined with the text() method:

// Get text of selected option
var selectedText = $("#titleSelect option:selected").text();
console.log(selectedText); // Output: "Mr" (if first option is selected)

Real-World Example with Event Handling

Here’s a practical example that shows the selected text when the dropdown changes:

<select id="countrySelect">
    <option value="us">United States</option>
    <option value="ca">Canada</option>
    <option value="uk">United Kingdom</option>
    <option value="au">Australia</option>
</select>
<p id="result"></p>

<script>
$("#countrySelect").change(function() {
    var selectedText = $(this).find("option:selected").text();
    var selectedValue = $(this).val();

    $("#result").html("You selected: " + selectedText + " (Value: " + selectedValue + ")");
});
</script>

You can see the output in the screenshot below.

jQuery Get Text of Selected Option

Method 2: Use find() with :selected

This approach is particularly useful when working with this context in event handlers:

$("#mySelect").change(function() {
    var selectedText = $(this).find("option:selected").text();
    console.log(selectedText);
});

This method is more efficient when you’re already working within a select element’s context because it doesn’t need to search the entire DOM.

Method 3: Direct Property Access

For modern browsers, you can also use native JavaScript properties:

var selectElement = document.getElementById("mySelect");
var selectedText = selectElement.options[selectElement.selectedIndex].text;

However, the jQuery approach is more readable and handles cross-browser compatibility better.

Complete Working Example: Dynamic Form

Here’s a comprehensive example that demonstrates getting selected option text in a real-world scenario:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Get Selected Option Text</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Product Selection Form</h2>

    <label for="category">Category:</label>
    <select id="category">
        <option value="">Choose a category</option>
        <option value="electronics">Electronics</option>
        <option value="clothing">Clothing</option>
        <option value="books">Books</option>
    </select>

    <label for="product">Product:</label>
    <select id="product">
        <option value="">Select category first</option>
    </select>

    <div id="selection-summary"></div>

    <script>
    $(document).ready(function() {
        // Handle category selection
        $("#category").change(function() {
            var categoryText = $(this).find("option:selected").text();
            var categoryValue = $(this).val();

            if (categoryValue) {
                // Populate products based on category
                populateProducts(categoryValue);
                updateSummary();
            }
        });

        // Handle product selection
        $("#product").change(function() {
            updateSummary();
        });

        function updateSummary() {
            var categoryText = $("#category option:selected").text();
            var productText = $("#product option:selected").text();

            if (categoryText && productText && categoryText !== "Choose a category") {
                $("#selection-summary").html(
                    "<h3>Your Selection:</h3>" +
                    "<p>Category: " + categoryText + "</p>" +
                    "<p>Product: " + productText + "</p>"
                );
            }
        }

        function populateProducts(category) {
            var products = {
                'electronics': ['Laptop', 'Smartphone', 'Tablet'],
                'clothing': ['T-Shirt', 'Jeans', 'Dress'],
                'books': ['Fiction', 'Non-Fiction', 'Technical']
            };

            var productSelect = $("#product");
            productSelect.empty().append('<option value="">Choose a product</option>');

            $.each(products[category], function(index, product) {
                productSelect.append('<option value="' + product.toLowerCase() + '">' + product + '</option>');
            });
        }
    });
    </script>
</body>
</html>

You can see the output in the screenshot below.

Get Text of Selected Option in jQuery

Best Practices and Common Issues

Here are some best practices and common issues that occur while getting the text of the selected option.

1. Always Check if an Option is Selected

Detects selected dropdown option and logs its text when changed.

$("#mySelect").change(function() {
    var selectedOption = $(this).find("option:selected");
    if (selectedOption.length > 0) {
        var text = selectedOption.text();
        console.log("Selected: " + text);
    } else {
        console.log("No option selected");
    }
});

2. Handle Multiple Select Elements

For multiple select dropdowns, you can get all selected texts:

$("#multiSelect option:selected").each(function() {
    console.log($(this).text());
});

3. Trim Whitespace

Always trim the text to remove any unwanted whitespace:

var selectedText = $("#mySelect option:selected").text().trim();

Performance Considerations

When dealing with large dropdowns or frequent changes, consider caching jQuery objects:

var $select = $("#mySelect");
$select.change(function() {
    var selectedText = $select.find("option:selected").text();
    // Process the selected text
});

Cross-Browser Compatibility

The jQuery methods shown in this tutorial work across all major browsers, including older versions of Internet Explorer. This makes jQuery a reliable choice for getting selected option text compared to newer JavaScript methods that might not be supported in legacy browsers.

Conclusion

Getting the text of a selected option in jQuery is easy using the :selected selector combined with the text() method. Whether you use $(“#mySelect option:selected”).text() or $(this).find(“option:selected”).text() depends on your specific use case and context.

Remember to always validate that an option is actually selected before trying to get its text, and consider trimming whitespace for cleaner results. With these techniques, you’ll be able to create more interactive and user-friendly web applications that respond appropriately to user selections.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.