Programming

값이 JQuery로 선택 목록에 있는지 확인하십시오.

procodes 2020. 8. 7. 19:05
반응형

값이 JQuery로 선택 목록에 있는지 확인하십시오.


JQuery를 사용하여 값이 드롭 다운 목록에 속하는지 여부를 어떻게 확인할 수 있습니까?


사용 특성이 선택기 같음

var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;

옵션의 값이 Javascript를 통해 설정된 경우 작동하지 않습니다. 이 경우 다음을 수행 할 수 있습니다.

var exists = false;
$('#select-box option').each(function(){
    if (this.value == 'bar') {
        exists = true;
        return false;
    }
});

당신 (또는 다른 사람)이 jQuery없이 작업하는 데 관심이있을 수있는 경우를 대비하여 :

var exists = false;
for(var i = 0, opts = document.getElementById('select-box').options; i < opts.length; ++i)
   if( opts[i].value === 'bar' )
   {
      exists = true; 
      break;
   }

또 다른 유사한 옵션이 있습니다. 제 경우에는 선택 목록을 작성할 때 다른 상자의 값을 확인하고 있습니다. 비교할 때 정의되지 않은 값으로 계속 실행되었으므로 다음과 같이 수표를 설정했습니다.

if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }

이 방법이 더 비싸지 않은지 모르겠습니다.


필터를 사용하지 않는 이유는 무엇입니까?

var thevalue = 'foo';    
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;

존재> 0이 참이고 존재 == 0이 거짓이기 때문에 느슨한 비교가 작동하므로 그냥 사용할 수 있습니다.

if(exists){
    // it is in the dropdown
}

또는 결합 :

if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
    // found
}

또는 각 선택 드롭 다운에 select-boxes 클래스가있는 경우 값을 포함하는 선택의 jquery 객체를 제공합니다.

var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();

if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){
//do stuff
}


나는 이것이 더 잘 작동하는 오래된 질문이라는 것을 알고 있습니다.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

이 예에서 볼 수 있듯이 고유 한 태그 데이터 드롭 다운 이름과 선택한 옵션의 값으로 검색하고 있습니다. 물론 이것들이 작동하는 데 필요하지는 않지만 다른 사람들이 다중 값 등을 검색 할 수 있도록 다른 사람들이 볼 수 있도록 포함했습니다.

참고 URL : https://stackoverflow.com/questions/2248976/check-if-value-is-in-select-list-with-jquery

반응형