[jquery] set dropdown value by text using jquery

I have a dropdown as:

<select id="HowYouKnow" >
  <option value="1">FRIEND</option>
  <option value="2">GOOGLE</option>
  <option value="3">AGENT</option></select>

In the above dropdown i know the text of the dropdown. How can set the value of the dropdown in document.ready with the text using jquery?

This question is related to jquery drop-down-menu

The answer is


This is a method that works based on the text of the option, not the index. Just tested.

var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');

Or, if there are similar values (thanks shanabus):

$("#HowYouKnow option").each(function() {
  if($(this).text() == theText) {
    $(this).attr('selected', 'selected');            
  }                        
});

$("#HowYouKnow").val("GOOGLE");

try this..

$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');

For the exact match use

    $("#HowYouKnow option").filter(function(index) { return $(this).text() === "GOOGLE"; }).attr('selected', 'selected');

contains is going to select the last match which might not be exact.


$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes

$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');

where XXX is the index of the one you want.


Here is an simple example:

$("#country_id").change(function(){
    if(this.value.toString() == ""){
        return;
    }
    alert("You just changed country to: " + $("#country_id option:selected").text() + " which carried the value for country_id as: " + this.value.toString());
});

var myText = 'GOOGLE';

$('#HowYouKnow option').map(function() {
    if ($(this).text() == myText) return this;
}).attr('selected', 'selected');

This is worked both chrome and firefox

set value in to dropdown box.

var given = $("#anotherbox").val();
$("#HowYouKnow").text(given).attr('value', given);

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.


The below code works for me -:

jQuery('[id^=select_] > option').each(function(){
        if (this.text.toLowerCase()=='text'){
            jQuery('[id^=select_]').val(this.value);
        }
});

jQuery('[id^=select_]') - This allows you to select drop down where ID of the drop down starts from select_

Hope the above helps!

Cheers S