240

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.

4
  • Hmm... the has in SLaks answer is useful, but the point in Floyds answer is also good... I dont know what to accept.
    – Hailwood
    Commented Sep 19, 2010 at 5:17
  • also, are these case sensitive? (im looking for case-insensitivity and can always just convert to lower
    – Hailwood
    Commented Sep 19, 2010 at 6: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. :) Commented Sep 19, 2010 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? Commented Jul 18, 2012 at 15:11

20 Answers 20

361

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

11
  • 29
    @KevinDeus: Why the downvote!? The answer was for the version of jQuery then! Commented Oct 25, 2011 at 14:59
  • 13
    Instead, use $('#test option').filter(function () { return $(this).html() == "B"; }).val(); Commented Mar 6, 2013 at 16:04
  • 89
    @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
    Commented Nov 14, 2013 at 23:51
  • 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
    Commented Mar 1, 2019 at 7: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); Commented May 15, 2019 at 15:57
155

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))')
8
  • 4
    :contains is not definitive now, is it? Commented Sep 19, 2010 at 2:38
  • What is the problem exactly with contains? Commented Nov 24, 2016 at 8:56
  • how would you do this with only selected options?
    – toddmo
    Commented Apr 27, 2017 at 14:45
  • 1
    Doesn't this also grab an option with 123abcdef?
    – Teepeemm
    Commented Mar 6, 2018 at 14:26
  • @Teepeemm Yes, that's the difference between the two top answers. The top only checks returns the option with only the specific text, this one returns the option that contains, but is not only, that specific text. Which, coincidentally, is what I actually need at the moment, so I am very glad posted it.
    – Lee A.
    Commented Mar 9, 2018 at 20:38
36

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;
});
3
  • 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
    Commented Nov 27, 2012 at 0: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
    Commented Jan 18, 2017 at 4: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. Commented Jan 25, 2018 at 20:08
25

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/

1
  • I'm replacing jquery with cash.js and was stuck trying to replace the jquery :contains selector. This did the trick.
    – train
    Commented Jan 21, 2023 at 1:56
17

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

4
  • 3
    You should add an explanation of why it's working as well. Commented Jul 15, 2015 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
    Commented Jun 2, 2016 at 22:30
  • 4
    Be sure you realize that this will find this option as well: <option>abcd</option>.
    – Charles
    Commented Jul 19, 2016 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
    Commented Sep 7, 2018 at 18:15
16

This is the best method for select text in dropdownlist.

$("#dropdownid option:contains(your selected text)").attr('selected', true);
1
  • 5
    As with similar answers, this will find an option with this is your selected text plus more.
    – Teepeemm
    Commented Mar 6, 2018 at 14:28
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 ) );
2
  • Makes sense with latest versions of jQuery
    – Fr0zenFyr
    Commented Jun 8, 2015 at 19:12
  • 3
    What's the point of "#my-Select" + " option"? Why not just "#my-Select option"?
    – Teepeemm
    Commented Mar 6, 2018 at 14:41
4

This work for me

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

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);
3

Use following

$('#select option:contains(ABC)').val();
2
  • 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 How to Answer. Commented Sep 15, 2015 at 13:29
  • 6
    if there some options: ABC, ABCD, ABCDEF, then?
    – hungndv
    Commented Nov 3, 2015 at 9:55
3

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');
    });
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);
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);
2

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

$("#select >option").filter( function()
{
    if ($(this).text() === "123")
    {
        $(this).prop("selected", true);
    }
});

Edit: In 2024, if you want to use a vanilla JS alternative, this is how the code will look like, very simple.

const sel = document.getElementById("cars");
        
// if you need the selected value of the option.
// this will return the numerical ID assigned to the selected car from my example.
// Ex. in case 'Saab' is selected, this will return the string "2".
sel.value;

// if you want the selected car name
const carName = sel.options[sel.selectedIndex].innerText;

// if you want the selected option
const selOption = sel.options[sel.selectedIndex];

// obviously, you van get the name and value from that option
const name = selOption.innerText;
const id = selOption.value;

// If you want to programmatically select the car "Saab", for example, set 'selectedIndex'
// propriety to the index value of the 'Saab' option in the option's list.
sel.selectedIndex = 1;
<select name="cars" id="cars">
  <option value="1">Volvo</option>
  <option value="2">Saab</option>
  <option value="3">Mercedes</option>
  <option value="4">Audi</option>
</select>

1
  • It's verbose, but in a good way. Much cleaner and more explicit than the other solutions using the text in the selector itself. Commented Jun 12, 2023 at 0:44
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]")
2
  • 5
    Interesting but unfortunately it doesn't seem to work (jQuery 1.10.2).
    – WynandB
    Commented Nov 15, 2013 at 0: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
    Commented Jun 8, 2015 at 19:15
1

use prop instead of attr

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

This will also work.

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

1
  • 2
    This will also grab the option ABC.
    – Teepeemm
    Commented Mar 6, 2018 at 14:30
-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;
     };
  }
-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.

-3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.