我有一个下拉列表:
<select id="HowYouKnow" > <option value="1">FRIEND</option> <option value="2">GOOGLE</option> <option value="3">AGENT</option></select>
在上面的下拉列表中,我知道下拉列表的文本。如何使用 jquery 设置 document.ready 中的下拉列表的值?
$("#HowYouKnow").val("GOOGLE");
$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');
where XXX is the index of the one you want.
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 option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes
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');
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.
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
This is worked both chrome and firefox
set value in to dropdown box.
var given = $("#anotherbox").val(); $("#HowYouKnow").text(given).attr('value', given);
try this..
$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');