If you’re working with jQuery and you want to select an <option>
based on it’s text value, rather than it’s [value]
attribute you can use the selector pattern: option[text="Option A"]
, where Option A
is the text label of the option you need to work with.
HTML
As an example, let’s say that you’re working with the following dropdown <select>
field:
<label for="colors">What's your favorite color?</label>
<select name="colors" id="colors">
<option value="1">Blue</option>
<option value="2">Red</option>
<option value="3">Green</option>
<option value="4">Yellow</option>
<option value="5">Black</option>
</select>
JavaScript/jQuery
To select an option based on it’s text color value, not it’s numbered value
, you would use this jQuery selector:
const option = $("select#colors option:contains('Red')");
If you need to check if it exists, you can use this approach:
if ( option.length ) {
console.log('An option with the text value of "Red" exists!');
}
If you need to capture the value from this <option>
:
const value = option.val();
If you wanted to find the text label or value of the currently selected option for a dropdown <select>
:
const selected = $("select#colors option:selected");
const text = selected.text();
const value = selected.val();
If you want to select a specific option in a <select>
element:
const option = $("select#colors option:contains('Red')");
option.prop('selected', true);
Conclusion
This goes beyond the original question, but I’ve found that when working with select elements and jQuery I often find myself using many of these approaches. Hopefully it provides a good resource for those still working with jQuery in a modern JavaScript environment. Regardless of what others say, it’s still a valuable tool for the right use cases.
If you’re still working with jQuery, which many websites still actively use despite it’s age, then this handy tip should help you select a specific <option>
from a dropdown <select>
based on it’s text label, opposed to it’s value.