235

I need to check if a <select> has an option whose text is equal to a specific value.

For example, if there's an <option value="123">abc</option>, I would be looking for "abc".

Is there a selector to do this?

Im looking for something similar to $('#select option[value="123"]'); but for the text.

Black
  • 18,150
  • 39
  • 158
  • 271
Hailwood
  • 89,623
  • 107
  • 270
  • 423
  • Hmm... the `has` in SLaks answer is useful, but the point in Floyds answer is also good... I dont know what to accept. – Hailwood Sep 19 '10 at 05:17
  • also, are these case sensitive? (im looking for case-insensitivity and can always just convert to lower – Hailwood Sep 19 '10 at 06:15
  • 1
    I use the JavaScript core function .toLowerCase() and compare, if case-insensitivity is required. Also, accept as answer the one that is most useful for your asked question. :) – Hari Pachuveetil Sep 19 '10 at 11:39
  • it don't work for a dropdown having multiselect API?? I tried all possible solutions bt no luck. I'm using eric hynd's multiselect dropdowm API. Can anyone solve this problem? – Chaitanya Chandurkar Jul 18 '12 at 15:11

20 Answers20

358

This could help:

$('#test').find('option[text="B"]').val();

Demo fiddle

This would give you the option with text B and not the ones which has text that contains B.

For recent versions of jQuery the above does not work. As commented by Quandary below, this is what works for jQuery 1.9.1:

$('#test option').filter(function () { return $(this).html() == "B"; }).val();

Updated fiddle

Halo
  • 1,730
  • 1
  • 8
  • 31
Hari Pachuveetil
  • 10,294
  • 3
  • 45
  • 68
  • 1
    this does not work with the latest versions of jquery (if you remove 'value=' from – KevinDeus Oct 24 '11 at 06:45
  • 28
    @KevinDeus: Why the downvote!? The answer was for the version of jQuery then! – Hari Pachuveetil Oct 25 '11 at 14:59
  • @Floyd Pink: Because it doesn't work anymore and hasn't been updated. – Stefan Steiger Mar 06 '13 at 15:46
  • 13
    Instead, use $('#test option').filter(function () { return $(this).html() == "B"; }).val(); – Stefan Steiger Mar 06 '13 at 16:04
  • 88
    @Quandary Still, it's not a valid reason to vote the answer down when a short comment would suffice. Or do you expect of him to retest all his answers for every new release of jQuery? – WynandB Nov 14 '13 at 23:51
  • @WynandB LOL I like your question about testing all his answers, good stuff, and good point! – Abdul Ahmad Mar 30 '15 at 21:14
  • @TahaRehmanSiddiqui: I just tested it with jQuery 1.9.1 and it is working for me. Can you tell me why you think it does not work? – Hari Pachuveetil May 14 '15 at 17:20
  • 4
    I think the downvote is due to the fact that the above example just findes the selected value, and does not set the selected value. – nivs1978 Mar 01 '19 at 07:13
  • 3
    nivs1987 is right, morehover I think you must use "text" instead of "html", something like val selVal= $('#test option').filter(function () { return $(this).text() == "B"; }).val(); then you must use selVal to select the wanted option with $('#test').val(selVal); – Alessandro Battistini May 15 '19 at 15:57
  • I found .text() is better than .html() since I needed to find options with an &. .html() read the option as & not &. – Aba Aug 04 '21 at 18:58
  • I tried both options but none worked in jQuery v3.5.1 – jgarcias Aug 25 '22 at 08:43
154

You can use the :contains() selector to select elements that contain specific text.
For example:

$('#mySelect option:contains(abc)')

To check whether a given <select> element has such an option, use the .has() method:

if (mySelect.has('option:contains(abc)').length)

To find all <select>s that contain such an option, use the :has() selector:

$('select:has(option:contains(abc))')
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
35

None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).attr('selected', 'selected');
        return false;
    }
    return true;
});
Dr. Hilarius
  • 1,134
  • 1
  • 14
  • 20
  • 1
    I think this is the best answer because it actually returns the correct results. But I can't help but think omitting `contains` altogether may actually speed things up. – styfle Nov 27 '12 at 00:05
  • 1
    This worked for me but in my scenario I could click edit on a grid multiple times so had to remove the selected attributed when there was no match otherwise the first option selected would remain for subsequent edits. else { $(this).attr('selected', ''); return false; } – esp Jan 18 '17 at 04:07
  • This solution worked for me but instead of setting option attribute, to actually change the select menu I needed to do: `$(this).parent().val($(this).val());` You could probably do both, but for me setting only the parent `val()` did the trick. – But those new buttons though.. Jan 25 '18 at 20:08
23

I faced the same issue below is the working code :

$("#test option").filter(function() {
    return $(this).text() =='Ford';
}).prop("selected", true);

Demo : http://jsfiddle.net/YRBrp/83/

Jaydeep Shil
  • 1,894
  • 22
  • 21
  • I'm replacing jquery with cash.js and was stuck trying to replace the jquery :contains selector. This did the trick. – train Jan 21 '23 at 01:56
16

This worked for me: $("#test").find("option:contains('abc')");

Phillip Dennis
  • 171
  • 1
  • 4
  • 3
    You should add an explanation of *why* it's working as well. – Hannes Johansson Jul 15 '15 at 12:59
  • @HannesJohansson Or he should at least explain how it's different than or adds something new to SLaks answer that's nearly five years older. ;^) – ruffin Jun 02 '16 at 22:30
  • 4
    Be sure you realize that this will find this option as well: . – Charles Jul 19 '16 at 17:35
  • Thanks this is definitly correct and what everyone missed is adding .attr('value'); to the end. This is the easiest way of actually getting the value to use in a dynamic manner! So the full code should like this. `$("#testselect").find("option:contains('option-text')").attr('value');` that way you can use an event like `.click()` to change a setting. – ChrisKsag Sep 07 '18 at 18:15
15

This is the best method for select text in dropdownlist.

$("#dropdownid option:contains(your selected text)").attr('selected', true);
HebeleHododo
  • 3,620
  • 1
  • 29
  • 38
sreejesh
  • 222
  • 2
  • 5
5

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );
user2561852
  • 97
  • 1
  • 2
4

This work for me

$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
3

Use following

$('#select option:contains(ABC)').val();
Dadaso Zanzane
  • 6,039
  • 1
  • 25
  • 25
  • 1
    the code you provided may resolve the issue but please add a brief description as to how this resolves the issue. Welcome to Stack Overflow, recommended reading [answer]. – Dan Beaulieu Sep 15 '15 at 13:29
  • 6
    if there some options: ABC, ABCD, ABCDEF, then? – hungndv Nov 03 '15 at 09:55
2

For jquery version 1.10.2 below worked for me

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });
Mir Gulam Sarwar
  • 2,588
  • 2
  • 25
  • 39
2

This works for me:

var result = $('#SubjectID option')
            .filter(function () 
             { return $(this).html() == "English"; }).val();

The result variable will return the index of the matched text value. Now I will just set it using it's index:

$('#SubjectID').val(result);
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
2

That was 10 years ago. Now jquery is EOL, we can use ordinary DOM for this simple job

document.getElementById("SomeSelectId").querySelectorAll("option").forEach(o => o.selected = o.innerText == text);
alphons
  • 105
  • 4
2

August 25, 2022.

For jQuery v3.5.1 what really worked for me is this:

$('#selectID option:contains("label")').prop('selected', true);

If you have the text in a variable, do this:

  ddText = 'Text to find';
  $('#selectID option:contains("' + ddText + '")').prop('selected', true);
jgarcias
  • 337
  • 3
  • 17
1

This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).

$('#mySelect option:[text=abc]")
Bartosz Firyn
  • 2,664
  • 2
  • 21
  • 18
  • 5
    Interesting but unfortunately it doesn't seem to work (jQuery 1.10.2). – WynandB Nov 15 '13 at 00:02
  • You would want to include that something like `$("#mySelect option").filter(function() { return this.text == "abc"; });` will work with latest versions of jQuery.. Or probably some other way which you prefer to use.. – Fr0zenFyr Jun 08 '15 at 19:15
1

This what worked for me on jquery V3.6.0 in 2022

$("#select >option").filter( function()
{
    if ($(this).text() === "123")
    {
        $(this).prop("selected", true);
    }
});
Dominick
  • 31
  • 7
  • It's verbose, but in a good way. Much cleaner and more explicit than the other solutions using the text in the selector itself. – Joshua Pinter Jun 12 '23 at 00:44
0

use prop instead of attr

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).prop('selected', 'selected');
        return false;
    }
    return true;
});
hmir
  • 97
  • 2
  • 7
-1

This will also work.

$('#test').find("select option:contains('B')").filter(":selected");

Tjcool
  • 391
  • 1
  • 3
  • 14
-1

As described in this answer, you can easily create your own selector for hasText. This allows you to find the option with $('#test').find('option:hastText("B")').val();

Here's the hasText method I added:

 if( ! $.expr[':']['hasText'] ) {
     $.expr[':']['hasText'] = function( node, index, props ) {
       var retVal = false;
       // Verify single text child node with matching text
       if( node.nodeType == 1 && node.childNodes.length == 1 ) {
         var childNode = node.childNodes[0];
         retVal = childNode.nodeType == 3 && childNode.nodeValue === props[3];
       }
       return retVal;
     };
  }
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
wbdarby
  • 1,129
  • 12
  • 12
-2

This works for me

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

Thanks for all the posts.

jayson.centeno
  • 835
  • 11
  • 15
-3

Either you iterate through the options, or put the same text inside another attribute of the option and select with that.

dekomote
  • 3,817
  • 1
  • 17
  • 13