Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set dropdown value by text using jquery [duplicate]

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?

like image 933
Prasad Avatar asked Dec 11 '09 15:12

Prasad


1 Answers

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');               }                         }); 
like image 110
Peter J Avatar answered Sep 19 '22 00:09

Peter J