2016-07-23 7 views
1

JQuery 1.11を使用すると、強制的に選択するオプションがありません。私は、オプションのテキストを知っている、と私はJQueryの選択メニューからオプションを強制的に選択するにはどうすればよいですか?

.find('option[text="Canada"]') 

を使用していますが、私の表現がコンソールに(出力は下記参照)、あなたがそこにあるはっきりと見ることができるという事実にもかかわらず、アイテムを見つけていません"カナダ"と読むオプション。

> $('.countryField') 
[<select id=​"user[address]​_country" name=​"user[address]​[country]​" class=​"countryField select-hidden">​…​</select>​<option value=​"0">​-- Select --​</option>​<option value=​"38">​Canada​</option>​…​<option value=​"249">​Zimbabwe​</option>​</select>​] 
> $('.countryField').find('option[text="Canada"]') 
[] 

私は間違っていますか?最終的には、指定されたテキストでオプションに対して「選択された」属性を有効にしたい(そして、他のすべてのオプションに「選択された」属性がないようにしたい)。

答えて

0

次のいずれかを試すことができます。

$(".countryField option").each(function(){ 
    if ($(this).text() == "Canada") 
    $(this).attr("selected","selected"); 
}); 


$(".countryField option[value='Canada']").attr("selected","selected"); 
+0

だから、これはテキストとオプションを選択しますが、それはまた、他のすべてのオプションの選択を解除しますか? –

+0

ドロップダウンがシングル選択の場合、答えはyesです –

+0

これは単一の選択ですが、私はあなたが上記のことを真実であると判断していません。つまり、属性 'selected = "selected"は以前に選択されたオプションのままです。 –

0

単純にjQuery valを使用して要素を選択できます。

$(function() { 
 
    $("#speed").selectmenu(); 
 

 
    // select the Canada option 
 
    $("#speed").val('Canada'); 
 
    $("#speed").selectmenu('refresh'); 
 
    
 
    // instead if you need to get the option with Canada text 
 
    var selectedEle = $("#speed option").filter(function(i, e) {return $(e).text() == 'Canada';}); 
 
    console.log(selectedEle[0].outerHTML); 
 
});
#speed { 
 
    width: 200px; 
 
}
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
 

 
<select name="speed" id="speed"> 
 
    <option>Slower</option> 
 
    <option>Slow</option> 
 
    <option selected="selected">Medium</option> 
 
    <option>Fast</option> 
 
    <option>Faster</option> 
 
    <option>Canada</option> 
 
</select>

関連する問題