2011-01-21 127 views

回答

37

使用:contains()(link)

$("select option:contains(text)").attr('selected', true); 

demo

+0

如果你需要做一個變量: var text =「Item 1」; (「選擇選項:包含(」+文本+「)」)。attr('selected',true); – ROFLwTIME 2012-05-18 15:22:00

9

有一個filter function on jQuery,你可以用它來獲得更具體的

$("select option").filter(function() { 
    return $(this).text() == "text_to_select"; 
}); 

這是要在文本中的「text_to_select」返回所有選項的東西元素。

+0

這應該是公認的答案。使用「contains」可能會匹配多個值,這可能很危險。 – 2016-03-16 19:42:01

2

我認爲這會爲你做的伎倆......

$("#selectId").find("option:contains('text')").each(function(){ 
    if($(this).text() == 'Text that should be matched') { 
    $(this).attr("selected","selected"); 
    } 
}); 
0

下面是我使用(這是不太一樣的代碼其他建議在這裏,並與jQuery v1.8.3一起使用)

var userToSearchFor = 'mike'; // Select any options containing this text 

$("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function() { 
    $(this).attr("selected", "selected"); 
}); 

<select id="ListOfUsers" ></select> 

希望這會有所幫助。

0

我有一個類似的情景下跌國家,州和城市。國家有「印度」以及「英屬印度洋領地」。 :contains()的問題在於它嘗試兩個匹配。我不喜歡的東西:

$('#country option').each(function(){ 
    if($(this).text() == 'India'){ 
     $(this).prop('selected', true).trigger('change'); 
    } 
}); 
0
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected'); 
相關問題