2013-08-27 2 views
8

자동 완성에서 목록 요소를 사용하지 않도록 설정할 수 없으므로 선택할 수 없으며 회색으로 표시됩니다.jQuery 자동 완성 목록에서 요소를 비활성화하는 방법

내가 jQuery를 UI 예제 페이지에서 가져온이 코드를 가지고 :

HTML :

<input id="tags" /> 

jQuery를 :

예를 들어
$(function() { 
    var availableTags = [ 
    "ActionScript", 
    "AppleScript", 
    "Asp", 
    "BASIC", 
    "C", 
    "C++", 
    "Clojure", 
    "COBOL", 
    "ColdFusion", 
    "Erlang", 
    "Fortran", 
    "Groovy", 
    "Haskell", 
    "Java", 
    "JavaScript", 
    "Lisp", 
    "Perl", 
    "PHP", 
    "Python", 
    "Ruby", 
    "Scala", 
    "Scheme" 
    ]; 
    $("#tags").autocomplete({ 
    source: availableTags 
    }); 
}); 

- 그것은이 가능 마지막을 사용하지 않도록 요소가 목록에 3 개 이상 있으면?

실제 코드에는 AJAX 요청이 있지만 자동 완성 상자에 20 개 이상의 결과가 표시되지 않으므로 이보다 더 많은 정보가 있으면 "검색 범위를 좁히십시오"와 같이 표시되어야합니다. 마지막 요소를 사용 불가능하게 만들 수 없으므로 선택할 수 없습니다 (그러나 마지막 요소 만 사용 불가능하게해야합니다).

위의 코드는 바이올린 데모와 함께 여기, 당신이 주변에 뭔가 할 수있는 몇 가지 트릭 작업으로 http://jsfiddle.net/m6zvf/

답변

20

나는 당신이 결과가 X보다 더 많은 경우 그것을 위해 사용자 정의 response 필요하고 방법을 렌더링 것, 메시지가 검색 범위를 좁힐 말과 비활성화 된 옵션을 추가 할 올바르게 이해한다면 :

Working fiddle

$(function() { 
    $("#tags").autocomplete({ 
     source: availableTags, 
     response: function (event, ui) { 
      //Check if we have more than 3 results 
      if (ui.content.length > 3) { 
       //Remove all elements until there are only 3 remaining (the use of slice() was not supported) 
       while (ui.content.length > 3) { 
        ui.content.pop(); 
       } 
       //Add message 
       ui.content.push({ 
        'label': 'Please narrow down your search', 
        'value': '' 
       }); 
      } 
     } 
    }).data("ui-autocomplete")._renderItem = function (ul, item) { 
     //Add the .ui-state-disabled class and don't wrap in <a> if value is empty 
     if(item.value ==''){ 
      return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul); 
     }else{ 
      return $("<li>") 
      .append("<a>" + item.label + "</a>") 
      .appendTo(ul); 
     } 
    }; 
}); 

당신은 RESPO에 대한 추가 정보를 위해 documentation을 참조 할 수 있습니다 NSE 방법은 _renderItem 기능은 문서화하지만 난

+2

이것은 키보드를 사용하여 요소를 아래로 스크롤 할 때를 제외하고는 거의 완벽하게 작동합니다. 비활성화 된 요소를 선택할 수 있습니다 (마우스로는 불가능 함). 키보드로도 그것을 선택하지 않으려면 어떻게해야합니까? – DHS

+0

@JohnMalli 업데이트보기, 키보드로 문제 해결, 또한 눈치 챘을 지 모르겠지만 옵션을 스크롤 가능하게 만드는 방법이 있습니다. 번호를 제한하는 대신 원하는 것이 있는지 몰라요. 옵션이 표시됩니다. http://jqueryui.com/autocomplete/#maxheight –

+0

목록에 선택 가능한 항목이 없으면 어떻게해야할까요? 따라서 표시된 유일한 항목은 UI 상태 비활성 항목 중 하나입니다. 1.12의 JQuery UI는 큰 소음을 던졌습니다. 1.9에서는 새로운 항목을 선택할 수 없습니다. – rythos42

2

:

JS

$("#tags").autocomplete({ 
     source: availableTags, 
     focus:function(e){e.stopPropagation();return false;}, 
     select:function(e){e.stopPropagation();return false;} 
    }); 

CSS

.ui-autocomplete .ui-state-focus{ 
    border:0 !important; 
    background:0 !important; 
} 

http://jsfiddle.net/techunter/zyGNQ/

편집 : 당신은 다음 렌더러를 수정해야

:

$("#tags").autocomplete({ 
     source: availableTags, 
     focus:function(e, ui){ 
      //if focusing on the extra elements return false thus doing nothing 
      return ui.item.idx<=2; 
     }, 
     select:function(e, ui){ 
      //if selecting on the extra elements return false thus doing nothing 
      return ui.item.idx<=2;} 
    }) .data("ui-autocomplete")._renderItem = function(ul, item) { 
     //small trick to get the current element index while the list is constructing, we set this as a helper for later usage inside the item. 
     item.idx=ul[0].childElementCount; 
      return $("<li>") 
       //if index is greater than 2 then we add a custom 'disable' class. this will help formating the disabled elements 
       .toggleClass('disable',ul[0].childElementCount>2) 
       //appending the element 
       .append("<a>" + item.label + "</a>").appendTo(ul); 
    }; 

EDIT 2, e.toElement 트릭

이벤트로보고이 동안 발견 :

$("#tags").autocomplete({ 
     source: availableTags, 
     focus: function (e, ui) { 
      $(e.toElement).toggleClass('ui-state-focus', ui.item.idx <= 2); 
      return ui.item.idx <= 2; 
     }, 
     select: function (e, ui) { 
      return ui.item.idx <= 2; 
     } 
    }).data("ui-autocomplete")._renderItem = function (ul, item) { 
     item.idx = ul[0].childElementCount; 
     return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul); 
    }; 

더 이상 CSS가 필요 없습니다.

http://jsfiddle.net/techunter/zyGNQ/

+0

CSS를 일부 조정이 필요한 사례 중 하나의 소스 코드를 발견하지만 당신은 그들 모두를 사용할 수있다 – TecHunter

+0

당신은 요점을 파악하지 않는 - 어떻게 마지막 하나를 비활성화 목록에 3 개 이상의 요소가 있다면? – DHS

+0

@JohnMalli 내 편집을 참조하십시오 :) – TecHunter