Which selector do I need to select an option by its text?

Viewed 273150

I need to check if a <select> has an option whose text is equal to a specific value.

For example, if there's an <option value="123">abc</option>, I would be looking for "abc".

Is there a selector to do this?

Im looking for something similar to $('#select option[value="123"]'); but for the text.

20 Answers

This works for me:

var result = $('#SubjectID option')
            .filter(function () 
             { return $(this).html() == "English"; }).val();

The result variable will return the index of the matched text value. Now I will just set it using it's index:

$('#SubjectID').val(result);

That was 10 years ago. Now jquery is EOL, we can use ordinary DOM for this simple job

document.getElementById("SomeSelectId").querySelectorAll("option").forEach(o => o.selected = o.innerText == text);

use prop instead of attr

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).prop('selected', 'selected');
        return false;
    }
    return true;
});

This what worked for me on jquery V3.6.0 in 2022

$("#select >option").filter( function()
{
    if ($(this).text() === "123")
    {
        $(this).prop("selected", true);
    }
});

August 25, 2022.

For jQuery v3.5.1 what really worked for me is this:

$('#selectID option:contains("label")').prop('selected', true);

If you have the text in a variable, do this:

  ddText = 'Text to find';
  $('#selectID option:contains("' + ddText + '")').prop('selected', true);
Related