Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find option text with wildcard jquery

Tags:

html

jquery

Trying to get the value 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 it might be the case I need to find the word Someone for example.

EDIT: Thank you all for your fast responses. Unfortunately I'll have to mark answered only 1

like image 937
viper Avatar asked Mar 24 '23 20:03

viper


2 Answers

jQuery doesn't have text selector, apart from that text is not an attribute, you can use :contains selector:

$('select[name="clauses"]').find("option:contains('OR')").val();
like image 147
undefined Avatar answered Apr 01 '23 07:04

undefined


text isn't an attribute, so you can't use an attribute selector on it. You can use contains instead:

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

This won't handle cases like DOOR. If you need to do that, use a regex with filter:

$('select[name="clauses"]').find('option').filter(function() {
    return $(this).text().match(/\bOR\b/);
}).val();
like image 44
Blender Avatar answered Apr 01 '23 05:04

Blender