How to disable element in jQuery autocomplete list

前端 未结 3 600
离开以前
离开以前 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:12

    If I understand correctly you want to add a disabled option with the message saying to narrow down the search when the results are more than X, for that you'd need a custom response and render methods:

    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  if value is empty
            if(item.value ==''){
                return $('
  • '+item.label+'
  • ').appendTo(ul); }else{ return $("
  • ") .append("" + item.label + "") .appendTo(ul); } }; });
  • You can refer to the documentation for more info on the response method, the _renderItem function is not documented but I found it in the source code of one of the examples

提交回复
热议问题