設置下拉值I有一個下拉爲:通過文本使用jquery
<select id="HowYouKnow" >
<option value="1">FRIEND</option>
<option value="2">GOOGLE</option>
<option value="3">AGENT</option></select>
在上述下拉我知道下拉的文本。如何設置document.ready下拉的值與使用jquery的文本?
設置下拉值I有一個下拉爲:通過文本使用jquery
<select id="HowYouKnow" >
<option value="1">FRIEND</option>
<option value="2">GOOGLE</option>
<option value="3">AGENT</option></select>
在上述下拉我知道下拉的文本。如何設置document.ready下拉的值與使用jquery的文本?
這是一種基於選項的文本而不是索引的方法。剛剛測試過。
var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');
或者,如果有相似值(感謝shanabus):
$("#HowYouKnow option").each(function() {
if($(this).text() == theText) {
$(this).attr('selected', 'selected');
}
});
$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes
僅此一想與索引一起使用而不是文本。 –
下面是一個簡單的例子:
$("#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');
對於精確匹配使用
$("#HowYouKnow option").filter(function(index) { return $(this).text() === "GOOGLE"; }).attr('selected', 'selected');
包含將要選擇可能不準確的最後匹配。
對於谷歌,GOOGLEDOWN,GOOGLEUP即類似樣的價值,你可以試試下面的代碼
$("#HowYouKnow option:contains('GOOGLE')").each(function() {
if($(this).html()=='GOOGLE'){
$(this).attr('selected', 'selected');
}
});
通過這種方式,可以減少循環迭代的數量,將在所有情況下工作。
下面的代碼對我的作品 - :
jQuery('[id^=select_] > option').each(function(){
if (this.text.toLowerCase()=='text'){
jQuery('[id^=select_]').val(this.value);
}
});
的jQuery( '[ID^= SELECT_]') - 這允許您選擇下拉其中下垂的ID下降從SELECT_開始
希望以上幫助!
乾杯 小號
這是在給下拉框中工作器和Firefox
設定值。
var given = $("#anotherbox").val();
$("#HowYouKnow").text(given).attr('value', given);
試試這個..
$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');
如果您的'select'列表包含具有相似文本值的'選項',即'' - 這對於如何處理此問題的想法是行不通的? – shanabus
爲了處理相似的值,你可以得到與索引[0]的第一次匹配(默認返回最後一個索引),如下所示:$(「#HowYouKnow option:contains(」+ theText +「)」)。attr 'selected','selected')[0]; – Asmussen
以上方法在jquery從1.9.1及更新版本中被打破。將.attr改爲.prop - >在這裏測試:http://jsfiddle.net/RB5wU/579/ –