developer tip

jquery [duplicate]를 사용하여 텍스트로 드롭 다운 값 설정

copycodes 2020. 9. 20. 10:05
반응형

jquery [duplicate]를 사용하여 텍스트로 드롭 다운 값 설정


이 질문에 이미 답변이 있습니다.

다음과 같은 드롭 다운이 있습니다.

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

위의 드롭 다운에서 드롭 다운의 텍스트를 알고 있습니다. jquery를 사용하여 텍스트로 document.ready의 드롭 다운 값을 어떻게 설정할 수 있습니까?


이것은 색인이 아닌 옵션 텍스트기반으로 작동하는 방법입니다 . 방금 테스트했습니다.

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

또는 비슷한 값이있는 경우 (shanabus에게 감사드립니다) :

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

정확한 일치 사용을 위해

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

포함은 정확하지 않을 수있는 마지막 일치를 선택합니다.


$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes

var myText = 'GOOGLE';

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

$("#HowYouKnow").val("GOOGLE");

GOOGLE, GOOGLEDOWN, GOOGLEUP의 경우 즉 유사한 종류의 값을 아래 코드에서 시도해 볼 수 있습니다.

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

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

이런 식으로 루프 반복 횟수를 줄일 수 있으며 모든 상황에서 작동합니다.


아래 코드는 나를 위해 작동합니다-:

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

jQuery('[id^=select_]') - This allows you to select drop down where ID of the drop down starts from select_

Hope the above helps!

Cheers S


try this..

$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');

Here is an simple example:

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

$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');

where XXX is the index of the one you want.


This is worked both chrome and firefox

set value in to dropdown box.

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

참고URL : https://stackoverflow.com/questions/1888931/set-dropdown-value-by-text-using-jquery

반응형