2009-12-11 27 views
77

設置下拉值I有一個下拉爲:通過文本使用jquery

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

在上述下拉我知道下拉的文本。如何設置document.ready下拉的值與使用jquery的文本?

回答

192

這是一種基於選項的文本而不是索引的方法。剛剛測試過。

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

或者,如果有相似值(感謝shanabus):

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

如果您的'select'列表包含具有相似文本值的'選項',即'' - 這對於如何處理此問題的想法是行不通的? – shanabus

+1

爲了處理相似的值,你可以得到與索引[0]的第一次匹配(默認返回最後一個索引),如下所示:$(「#HowYouKnow option:contains(」+ theText +「)」)。attr 'selected','selected')[0]; – Asmussen

+4

以上方法在jquery從1.9.1及更新版本中被打破。將.attr改爲.prop - >在這裏測試:http://jsfiddle.net/RB5wU/579/ –

1
$("#HowYouKnow").val("GOOGLE"); 
+0

$(文件)。就緒(函數(){ $( 「#HowYouKnow」)VAL( 「GOOGLE」); }); 設置值也不知道爲什麼我下了票! – dell

+10

也許是因爲只有當你的'option'值與文本相同時纔有效。所以在OP的示例中,GOOGLE文本選項的值爲「2」,因此它不起作用。 – shanabus

+0

最好的解決方案:) – Subodh

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

其中XXX是你想要的一個指數。

+0

如何獲取文本的索引? – Prasad

+0

看到我的答案...測試和工作。 –

+3

問題是通過文本設置下拉值,而不是通過索引。 – Cheung

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

僅此一想與索引一起使用而不是文本。 –

0

下面是一個簡單的例子:

$("#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()); 
}); 
1
var myText = 'GOOGLE'; 

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

對於精確匹配使用

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

包含將要選擇可能不準確的最後匹配。

1

對於谷歌,GOOGLEDOWN,GOOGLEUP即類似樣的價值,你可以試試下面的代碼

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

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

通過這種方式,可以減少循環迭代的數量,將在所有情況下工作。

1

下面的代碼對我的作品 - :

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

的jQuery( '[ID^= SELECT_]') - 這允許您選擇下拉其中下垂的ID下降從SELECT_開始

希望以上幫助!

乾杯 小號

0

這是在給下拉框中工作器和Firefox

設定值。

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

試試這個..

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