set dropdown value by text using jquery
JqueryDrop Down-MenuJquery Problem Overview
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?
Jquery Solutions
Solution 1 - Jquery
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');
}
});
Solution 2 - Jquery
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.
Solution 3 - Jquery
$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes
Solution 4 - Jquery
var myText = 'GOOGLE';
$('#HowYouKnow option').map(function() {
if ($(this).text() == myText) return this;
}).attr('selected', 'selected');
Solution 5 - Jquery
try this..
$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');
Solution 6 - Jquery
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.
Solution 7 - Jquery
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
Solution 8 - Jquery
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());
});
Solution 9 - Jquery
$("#HowYouKnow").val("GOOGLE");
Solution 10 - Jquery
$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');
where XXX is the index of the one you want.
Solution 11 - Jquery
This is worked both chrome and firefox
set value in to dropdown box.
var given = $("#anotherbox").val();
$("#HowYouKnow").text(given).attr('value', given);