21

How would I select my dropdown list item by text rather than value?

I want to select a dropdown item by text with jQuery.

0

6 Answers 6

41

use :contains()(link)

$("select option:contains(text)").attr('selected', true);

demo

Sign up to request clarification or add additional context in comments.

6 Comments

If you need to do a variable: var text = "Item 1"; $("select option:contains(" + text + ")").attr('selected', true);
This works fine unless you have similar items. For example, if you search for "item" and the options are "item 1", "item 2", etc. then you will get more than one result
with newer versions of jquery (1.6.1+?), use prop('selected',true) instead of attr('selected',true)
@PostureOfLearning : any solution for similar items?
OK I was able to do it and posted my answer.
|
10

There is a filter function on jQuery that you can use to get elements with something more specific

$("select option").filter(function() {
    return $(this).text() == "text_to_select";
});

This is going to return all options with the "text_to_select" in the text.

1 Comment

THIS should be the accepted answer. Using "contains" could match several values, which could be dangerous.
3

i think this will do the trick for you...

$("#selectId").find("option:contains('text')").each(function(){
  if( $(this).text() == 'Text that should be matched' ) {
    $(this).attr("selected","selected");
  }
});

Comments

0

Here's the code I use (it's not quite the same as the other suggestions here, and works with jQuery v1.8.3)

var userToSearchFor = 'mike';   //  Select any options containing this text

$("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function () {
   $(this).attr("selected", "selected");
});

<select id="ListOfUsers" ></select>

Hope this helps.

Comments

0

I had a similar scenario with dropdowns for country, state and city. Country had "India" as well as "British Indian Ocean Territory". The issue with :contains() is that it attempts on both matches. I did something like:

$('#country option').each(function(){
    if($(this).text() == 'India'){
        $(this).prop('selected', true).trigger('change');
    }
});

Comments

0
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.