2012-01-12 67 views
1

所以我有一個標準的選擇下拉菜單。 select中的一個選項(最後一個)我有一個文本字符串 - var abc。Jquery Javascript HTML選擇

<select id="exampleselect"> 
    <option>123</option> 
    <option>xyz</option> 
    <option>ABC</option> 
</select> 

var abc = "ABC"; 

我想要做的就是通過選擇搜索,找到對VAR ABC匹配,則VAR ABC的比賽改變爲所選的選項。

我已經試過什麼:

//gets all the options from the select 
var selectoptions = $('#exampleselect').find('option').text(); 

//if there is a match of var abc to any of the options in the select 
if (selectoptions == abc) 
    { 
     //work out how to get the index/eq of the matched element 

     //put matched element as selected value 
     $('#exampleselect').val(matchedelementindex); 
    } 
+0

所以你想讓最後一個選項是動態的嗎?價值將如何確定? – 2012-01-12 11:05:40

回答

3

直播example支持。通過使用:contains()選擇

var myVar = 'xyz'; 

$('#exampleselect option').each(function(e) { 
    var $this = $(this); 
    if ($this.text() === myVar) { 
     $this.prop('selected', true); 
     return false; // stops the iteration 
    } 
}); 

你也能做到這一點的一條線:

當你不使用屬性的值,你可以使用此代碼。 這會,如果你有文字「ABC」的選項,另一個爲「ABCD」可能無法正常工作:

$('#exampleselect option:contains('+myVar+')').prop('selected', true); 

雖然,我會建議你把值屬性添加到您的選項元素:

<select id="exampleselect"> 
    <option value="123">123</option> 
    <option value="xyz">xyz</option> 
    <option value="ABC">ABC</option> 
</select> 

這種方式,你可以這樣做:

$('#exampleselect').val(myVar); 
+1

+1表示使用'value'。一個更簡潔的解決方案。 – 2012-01-12 11:13:12

1

試試這個:

var abc = "ABC"; 
$("#exampleselect option").each(function() { 
    if ($(this).text() == abc) { 
     $(this).attr("selected", true); 
     return false; // exit each loop 
    } 
}) 

還是這個,雖然這是略少可讀性:

var abc = "ABC"; 
$("#exampleselect option").each(function() { 
    $(this).attr("selected", $(this).text() == abc); 
}) 
0

這撥弄可以幫助你。 您可以通過CSS選擇實現這一目標,其是由jQuery的

var searched="abc"; 
$('select option['+searched+']').attr("selected","selected"); 

http://jsfiddle.net/7EzqU/

0
// iterate all select options using jquery .each method  
$('#exampleselect option').each(function() { 

    // check if current option text is equal to 'ABC' 
    if ($(this).text() == 'ABC') { 

     // get index of option 
     var index = $('#exampleselect').index($(this)) 

     // set selectedIndex property to change to this option 
     $('#exampleselect').prop('selectedIndex', index); 
    } 
})