set dropdown value by text using jquery

Prasad picture Prasad · Dec 11, 2009 · Viewed 194.6k times · Source

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?

Answer

Peter J picture Peter J · Dec 11, 2009

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