jQuery Select Option by Text
Usually, we select the options of the HTML dropdown box using value. But have you ever thought about selecting an option through the text of that option? So, in this article, we’re going to see how to select options by text in jQuery.
Now let’s see an example:
Below is our HTML code for the drop-down list with 3 options:
<select>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<button id="onclick"> Select </button>
The jQuery code is
$("#onclick").click(function() {
// Selecting option with text "Banana"
$("select option:contains('Banana')").prop("selected", true);
});
When the button is clicked, the code finds all the <option> elements within an <select> element that contains the text “Banana” and selects them.
Here, the jQuery selector selects an element that contains the text “Banana”. It searches for options where the text inside the option tag contains the word “Banana”. Then sets the “selected” property of the selected options to true, effectively selecting those options. It marks the options with the text “Banana” as selected, the line is
$("select option:contains('Banana')").prop("selected", true);
So, the code adds the attribute “selected” to the “Banana”.
We have also some alternative methods to select options by text in jQuery instead of this.
Filtering Options
Here, we have used the filter() method instead of contains(). It filters the selected options based on a condition specified within the function. In this case, the condition is $(this).text() === "Banana"
, which checks if the text content of the current option matches the string “Banana”.
$("#onclick").click(function() {
// Selecting option with text "Banana"
$("select option").filter(function() {
return $(this).text() === "Banana";
}).prop("selected", true);
});
Traversing the Options
In this example, we’ve selected the option using each() loop and if condition. The loop executes the provided function for each option and the condition checks if the text content of the current option is equal to the string “Cherry”.
$("#onclick").click(function() {
// Selecting option with text "Cherry"
$("select option").each(function() {
if ($(this).text() === "Cherry") {
$(this).prop("selected", true);
return false; // Exit the loop early
}
});
});
So, you can Select Option by Text in jQuery by using the above three ways.