jQuery Set Selected Option by Text

Setting a dropdown option as selected by its text value is a common requirement in web development. This comprehensive tutorial will show you multiple methods to accomplish this using jQuery, complete with practical examples and best practices.

Understand the Problem

When working with HTML select elements, you often need to programmatically set the selected option based on its display text rather than its value attribute. This is particularly useful when:

  • You receive text data from APIs or user input
  • The option values are IDs or codes, but you want to select by human-readable text
  • You’re working with dynamically generated dropdowns

Here’s a typical HTML select element we’ll work with:

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

Method 1: Use :contains() Selector

The simplest approach uses jQuery’s :contains() pseudo-selector to find options by their text content:

// Select option by text using :contains()
function selectByText(selectId, text) {
    $('#' + selectId + ' option:contains("' + text + '")').prop('selected', true);
}

// Usage example
selectByText('countrySelect', 'Canada');

// Alternative one-liner
$('#countrySelect option:contains("United Kingdom")').prop('selected', true);

You can see the output in the screenshot below.

jQuery Set Selected Option by Text

Pros: Simple and concise
Cons: Case-sensitive and may match partial text

Method 2: Use each() Method

For more precise control, iterate through all options and compare text values:

function selectOptionByText(selectId, targetText) {
    $('#' + selectId + ' option').each(function() {
        if ($(this).text() === targetText) {
            $(this).prop('selected', true);
            return false; // Break the loop
        }
    });
}

// Usage
selectOptionByText('countrySelect', 'Australia');

You can see the output in the screenshot below.

Set Selected Option by Text jQuery

This method provides exact text matching and better control over the selection process.

Method 3: Use filter() Method

The filter() method offers a clean, functional approach:

function setSelectedByText(selector, text) {
    $(selector).find('option').filter(function() {
        return $(this).text() === text;
    }).prop('selected', true);
}

// Usage examples
setSelectedByText('#countrySelect', 'United States');

// Case-insensitive version
function setSelectedByTextIgnoreCase(selector, text) {
    $(selector).find('option').filter(function() {
        return $(this).text().toLowerCase() === text.toLowerCase();
    }).prop('selected', true);
}

setSelectedByTextIgnoreCase('#countrySelect', 'united states');

You can see the output in the screenshot below.

Set Selected Option by Text in jQuery

Method 4: Custom Function Approach

Here’s a robust, reusable function that handles multiple scenarios:

$.fn.selectByText = function(text, options) {
    var settings = $.extend({
        caseSensitive: true,
        exactMatch: true,
        triggerChange: true
    }, options);

    return this.each(function() {
        var $select = $(this);
        var $option = $select.find('option').filter(function() {
            var optionText = $(this).text();
            var searchText = text;

            if (!settings.caseSensitive) {
                optionText = optionText.toLowerCase();
                searchText = searchText.toLowerCase();
            }

            if (settings.exactMatch) {
                return optionText === searchText;
            } else {
                return optionText.indexOf(searchText) !== -1;
            }
        });

        if ($option.length > 0) {
            $option.prop('selected', true);
            if (settings.triggerChange) {
                $select.trigger('change');
            }
        }
    });
};

// Usage examples
$('#countrySelect').selectByText('Canada');
$('#countrySelect').selectByText('united', {
    caseSensitive: false,
    exactMatch: false
});

You can see the output in the screenshot below.

Set Selected Option by jQuery Text

Handle Edge Cases

Let me show you how to handle edge cases.

Multiple Options with Same Text

Selects the **first** matching `<option>` when several share the same visible text.

function selectFirstByText(selector, text) {
    $(selector).find('option').filter(function() {
        return $(this).text() === text;
    }).first().prop('selected', true);
}

Option Not Found Handling

Safely attempts selection, runs a callback, and falls back (or warns) if no match.

function selectByTextWithCallback(selector, text, callback) {
    var $option = $(selector).find('option').filter(function() {
        return $(this).text() === text;
    });

    if ($option.length > 0) {
        $option.prop('selected', true);
        if (callback) callback(true, $option);
    } else {
        console.warn('Option with text "' + text + '" not found');
        if (callback) callback(false, null);
    }
}

// Usage
selectByTextWithCallback('#countrySelect', 'Germany', function(found, option) {
    if (found) {
        console.log('Successfully selected:', option.text());
    } else {
        console.log('Option not found, selecting default');
        $('#countrySelect option:first').prop('selected', true);
    }
});

Work with Dynamic Content

Waits or observes DOM changes (timeout/MutationObserver) to select options added after load.

$(document).ready(function() {
    // Wait for dynamic content to load
    setTimeout(function() {
        $('#dynamicSelect').selectByText('Dynamic Option');
    }, 1000);

    // Or use MutationObserver for real-time updates
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                $('#dynamicSelect').selectByText('Target Option');
            }
        });
    });

    observer.observe(document.getElementById('dynamicSelect'), {
        childList: true
    });
});

Best Practices

Here are some best practices that you need to follow while setting selected option by text.

1. Always Trigger Change Events

Ensures that selecting an option also triggers any associated change event listeners.

$('#countrySelect option:contains("Canada")').prop('selected', true).parent().trigger('change');

2. Error Handling

Provides a safe way to select options with try-catch to handle missing elements or options gracefully.

function safeSelectByText(selector, text) {
    try {
        var $select = $(selector);
        if ($select.length === 0) {
            throw new Error('Select element not found: ' + selector);
        }

        var $option = $select.find('option:contains("' + text + '")');
        if ($option.length === 0) {
            throw new Error('Option not found: ' + text);
        }

        $option.prop('selected', true);
        $select.trigger('change');
        return true;
    } catch (error) {
        console.error('Error selecting option:', error.message);
        return false;
    }
}

3. Performance Optimization

For better performance with large dropdowns:

function optimizedSelectByText(selector, text) {
    var select = document.querySelector(selector);
    var options = select.options;

    for (var i = 0; i < options.length; i++) {
        if (options[i].text === text) {
            select.selectedIndex = i;
            $(select).trigger('change');
            return true;
        }
    }
    return false;
}

Setting selected options by text in jQuery can be accomplished through various methods, each with its own advantages. The :contains() selector offers simplicity, while methods like filter() and each() provide more control. Choose the approach that best fits your specific use case, considering factors like case sensitivity, partial matching, and error handling requirements.

Remember to always trigger change events when programmatically selecting options to ensure proper form validation and event handling in your applications.

You may 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.