How to disable element in jQuery autocomplete list

前端 未结 3 586
离开以前
离开以前 2020-12-17 16:14

Is it possible to disable a list element in an autocomplete, so it is not chooseable (and greyed out)?

I have this code, taken from the jQuery UI example page:

3条回答
  •  粉色の甜心
    2020-12-17 17:13

    With some trick work you could do something around :

    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/

    EDIT :

    You need to modify the renderer then :

    $( "#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 $( "
  • " ) //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( "" + item.label + "" ).appendTo( ul ); };
  • EDIT 2, e.toElement trick

    found this while looking into the event :

    $("#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 $("
  • ").append("" + item.label + "").appendTo(ul); };
  • No more need of the CSS.

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

提交回复
热议问题