Find option text with wildcard jquery

Trying to get a value of 3 What am I doing wrong with my jQuery?

JQuery

 $('select[name="clauses"]').find("option[text~='OR']").val() 

HTML:

 <select multiple="" name="clauses" > <option value="0"> </option> <option value="1"> ( </option> <option value="2"> ( Someone</option> <option value="3"> OR Something ) )</option> <option value="4">AND Something</option> </select> 

I used ~ because maybe I need to find the word Someone, for example.

EDIT: Thank you all for your quick answers. Unfortunately, I have to mention only 1

+4
source share
3 answers

jQuery does not have a text selector, except that text not an attribute, you can use the :contains selector:

 $('select[name="clauses"]').find("option:contains('OR')").val(); 
+4
source

text not an attribute, so you cannot use an attribute selector on it. Instead, you can use contains :

 $('select[name="clauses"]').find("option:contains('OR')").val() 

This will not handle cases like DOOR . If you need to do this, use a regex with filter :

 $('select[name="clauses"]').find('option').filter(function() { return $(this).text().match(/\bOR\b/); }).val(); 
+2
source

Your approach assumes that the <option> elements have a text attribute, which is not so, what you are looking for is a selector :contains() , as you can see in the jQuery Documentation :

Description: Select all elements containing the specified text.

So try with:

 $('select[name="clauses"]').children('option:contains(OR)').val(); 

Also keep in mind that the <option> elements are direct child elements of the <select> , so there is no need to use .find() in this case ...

Jsbin demo

+1
source

Source: https://habr.com/ru/post/1482464/


All Articles