web-dev-qa-db-ja.com

jqueryを使用してテキストでドロップダウン値を設定します

私はドロップダウンを持っています:

<select id="HowYouKnow" >
  <option value="1">FRIEND</option>
  <option value="2">GOOGLE</option>
  <option value="3">AGENT</option></select>

上記のドロップダウンでは、ドロップダウンのテキストがわかります。 jqueryを使用してテキストでdocument.readyのドロップダウンの値を設定するにはどうすればよいですか?

83
Prasad

これは、インデックスではなく、オプションのtextに基づいて機能するメソッドです。テスト済み。

var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');

または、同様の値がある場合(shanabusに感謝):

$("#HowYouKnow option").each(function() {
  if($(this).text() == theText) {
    $(this).attr('selected', 'selected');            
  }                        
});
207
Peter J

完全一致の使用

    $("#HowYouKnow option").filter(function(index) { return $(this).text() === "GOOGLE"; }).attr('selected', 'selected');

containsは、正確ではない可能性のある最後の一致を選択します。

13
Parham
$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes
5
Vinay saini
var myText = 'GOOGLE';

$('#HowYouKnow option').map(function() {
    if ($(this).text() == myText) return this;
}).attr('selected', 'selected');
2
Matthew Feerick

GOOGLE、GOOGLEDOWN、GOOGLEUPについては、以下のコードで試すことができる同様の種類の値

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

このようにして、ループの反復回数を減らすことができ、あらゆる状況で機能します。

1
juhi

以下のコードは私のために働く-:

jQuery('[id^=select_] > option').each(function(){
        if (this.text.toLowerCase()=='text'){
            jQuery('[id^=select_]').val(this.value);
        }
});

jQuery( '[id ^ = select _]')-これにより、ドロップダウンのIDが始まるドロップダウンを選択できますselect _

上記がお役に立てば幸いです!

乾杯

1
stevensagaar

これを試して..

$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');
1
Divy
$("#HowYouKnow").val("GOOGLE");
1
dell

これはchromeとfirefoxの両方で機能します

ドロップダウンボックスに値を設定します。

var given = $("#anotherbox").val();
$("#HowYouKnow").text(given).attr('value', given);
0
Naveenbos

以下に簡単な例を示します。

$("#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());
});
0
fullstacklife