2012-01-12 4 views
1

を選択する標準のドロップダウンリストがあります。 select(最後のもの)のオプションの1つとして、テキスト文字列-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戦を見つけ、選択して検索しています。これは少し読みにくくなるが、

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

最後のオプションを動的にしますか?値はどのように設定されますか? –

答えて

3

exampleによってサポートされているCSSセレクタによってこれを達成することができます。

あなたはvalue属性を使用していないとして、あなたはこのコードを使用することができます

var myVar = 'xyz'; 

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

ます。また:contains()セレクタを使って、1行でそれを行うことができます。 しかし、これはあなたがテキスト「ABC」と「ABCD」との相互の選択肢がある場合に動作しない可能性があります:

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

もののを、私はあなたのオプション要素にvalue属性を追加することをお勧めします:あなたが行うことができます

<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'の使用を示唆しています。はるかに簡潔な解決策です。 –

1

はこれを試してみてください:私が試した何

。 あなたはjQueryの

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

http://jsfiddle.net/7EzqU/

0

このバイオリンはあなたを助けるかもしれ

//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
// 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); 
    } 
})