programing

jQuery - 텍스트 설명을 통해 선택한 컨트롤의 값을 설정합니다.

shortcode 2022. 11. 4. 21:59
반응형

jQuery - 텍스트 설명을 통해 선택한 컨트롤의 값을 설정합니다.

선택 컨트롤이 있고 javascript 변수에는 텍스트 문자열이 있습니다.

jQuery를 사용하여 선택 컨트롤의 선택된 요소를 텍스트 설명과 함께(없는 값이 아닌) 항목으로 설정합니다.

값으로 설정하는 것은 매우 간단하다는 것을 알고 있습니다.

$("#my-select").val(myVal);

그러나 나는 텍스트 설명으로 그것을 하는 것에 조금 당황했다.텍스트 설명에서 값을 빼낼 방법이 있을 것 같은데, 금요일 오후에 머리가 너무 복잡해서 그걸 알아낼 수가 없어요.

jQuery v1.6에 대한 설명으로 선택+

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

jQuery 버전이 1.6보다 작거나 1.4보다 크거나 같음

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

이 방법은 1.6보다 크지만 1.9보다 작은 버전에서는 사용할 수 있지만 1.6부터는 권장되지 않습니다.jQuery 1.9+에서는 동작하지 않습니다.


이전 버전

val()두가가가사사사합합합합합합합

$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

테스트해 본 적은 없지만, 당신에게는 효과가 있을지도 몰라요.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

이거 드셔보세요.myText 텍스트 옵션을 선택합니다.

$("#my-Select option[text=" + myText +"]").prop("selected", true);

이 방법으로 실행한다(jQuery 1.9.1).

$("#my-select").val("Dutch").change();

주의: 변경()을 잊지 마십시오.그 때문에 오랫동안 검색해야 했습니다.

$("#myselect option:contains('YourTextHere')").val();

텍스트 설명이 포함된 첫 번째 옵션 값이 반환됩니다.이것을 테스트해, 동작.

모든 jQuery 버전의 복잡성을 피하기 위해 솔직히 이 매우 간단한 javascript 함수 중 하나를 사용하는 것을 추천합니다.

function setSelectByValue(eID,val)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].value==val) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

function setSelectByText(eID,text)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].text==text) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

이 행은 유효했습니다.

$("#myDropDown option:contains(myText)").attr('selected', true);

오래된 투고인 것은 알지만 jQuery 1.10.3과 위의 솔루션을 사용하여 텍스트로 선택할 수 없었습니다.결국 다음 코드(스폴슨 솔루션의 변형)를 사용하게 되었습니다.

      var textToSelect = "Hello World";

      $("#myDropDown option").each(function (a, b) {
            if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
        });

도움이 됐으면 좋겠는데

 $("#Test").find("option:contains('two')").each(function(){
     if( $(this).text() == 'two' ) {
        $(this).attr("selected","selected");
     }
 });

if 문이 "two"와 정확히 일치하고 "two three"가 일치하지 않습니다.

1.7+를 사용하는 가장 쉬운 방법은 다음과 같습니다.

$("#myDropDown option:text=" + myText +"").attr("selected", "selected"); 

1.9+

$("#myDropDown option:text=" + myText +"").prop("selected", "selected"); 

테스트 및 동작.

여기 아주 간단한 방법이 있습니다. 그것을 사용하세요.

$("#free").val("y").change();

jquery selectedbox 플러그인 보기

selectOptions(value[, clear]): 

로서 합니다.$("#myselect2").selectOptions("Value 1"); " " " " "$("#myselect2").selectOptions(/^val/i);

옵션도 수 .$("#myselect2").selectOptions("Value 2", true);

그냥 옆길로.선택한 값이 설정되지 않았습니다.그리고 인터넷을 샅샅이 뒤져봤죠.사실 웹 서비스에서 데이터를 가져오고 있었기 때문에 웹 서비스에서 콜백한 후 값을 선택해야 했습니다.

$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected'); 
$("#SelectMonth").selectmenu('refresh', true);

그래서 셀렉터의 새로 고침이 내가 놓친 유일한 것이었다.

그걸 이용해서 알았어요.attr원하지 않을 때 여러 옵션을 선택할 수 있습니다. 해결 방법은 다음과 같습니다.prop:

$("#myDropDown option:text=" + myText +"").prop("selected", "selected");

위의 예에서 문제가 발생했는데, Select Box 값이 6자 고정 길이의 문자열로 미리 채워져 있는데 전달된 파라미터가 고정 길이가 아니기 때문에 문제가 발생하였습니다.

rpad 기능은 지정된 길이로 지정된 문자를 사용하여 문자열을 오른쪽 패딩합니다.따라서 매개 변수를 채운 후 작동합니다.

$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 
 $('#theYear').on('change', function () {
 FY = $(this).find('option:selected').text();
 $('#theFolders').each(function () {
     $('option:not(:contains(' + FY + '))', this).hide();
 });
 $('#theFolders').val(0);
});

$('#theYear').on('mousedown', function () {
 $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});

매우 안절부절못하고 다른 것은 작동하지 않는 것 같았다

$('select [name$="드롭다운"]).children().text("Mr").prop("selected", true);

날 위해 일했어

해라

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>

이 받아들여진 답변은 올바르지 않은 것 같습니다만, .val('newValue')는 함수에 대해 올바른 것입니다.이 함수의 이름으로 선택 항목을 검색하려고 하면 문제가 생깁니다.그래서 id와 classname을 사용하여 요소를 가져와야 했습니다.

이것은 쉬운 선택입니다.목록 옵션을 설정한 다음 텍스트를 선택한 값으로 설정하십시오.

$("#ddlScheduleFrequency option").selected(text("Select One..."));

만약 당신이 ID로 select를 바인드하려고 한다면, 나는 다음 코드를 사용할 수 있었다.

<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
    <option value="0" class="notag" id="id0_0">--Select--</option>
    <option class="notag" value="338" id="id0_338"  >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro  > £114.00</option>
    <option class="notag" value="282" id="id0_282"  >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00</option>
    <option class="notag" value="265" id="id0_265"  >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro  > £114.00</option>
    <option class="notag" value="101" id="id0_101"  >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI  > £114.00</option>
    <option class="notag" value="105" id="id0_105"  >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI  > £114.00</option></select>

그리고 이것은 TE JS 코드입니다.

$( document ).ready(function() {
      var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00";
      alert(text);
$("#groupsel_0 option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text;
}).prop('selected', true);
});

선택 상자의 자식을 가져와 이들을 루프합니다.필요한 자식을 찾으면 선택한 옵션으로 설정하고 false를 반환하여 루프를 중지합니다.

언급URL : https://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description

반응형