Alcove
Alcove

Reputation: 39

jQuery if option text contains string, select it

I want to achieve something similar to this: select an option with partial matching in option value

But instead of the option being selected based on the value, I want it to be based on the text inside.

For example, I have the following dropdown list. I want that if the option text contains "John", then select it.

<select>
    <option>Jane Doe</option>
    <option>Mary Sue</option>
    <option>John Smith</option>
    <option>Gary Stu</option>
</select>

Upvotes: 2

Views: 6683

Answers (1)

guradio
guradio

Reputation: 15565

  1. Use :contains()

    Description: Select all elements that contain the specified text.

$("select option:contains(John)").prop("selected","selected")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>Jane Doe</option>
<option>Mary Sue</option>
<option>John Smith</option>
<option>Gary Stu</option>
</select>

Upvotes: 5

Related Questions