How to disable element in jQuery autocomplete list

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

    Arrow keys should be resolved too. Disabled items should be skipped. Disabled items are marked by attribute in source. It can be done by changing of active item nad setting corresponding class:

        $( "#tags" ).autocomplete({
        source: [
            {value: "ActionScript", disabled: false},
            {value: "AppleScript", disabled: true},
            {value: "Asp", disabled: false},
            {value: "BASIC", disabled: true},
            {value: "Erlang", disabled: false},
            {value: "Fortran", disabled: true}
        ],
        create: function () {
            $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                let value = item.value;
                let listItem;
                if (item.disabled) {
                    listItem = $('
  • ' + value + '
  • ') .appendTo(ul); } else { listItem = $("
  • ") .append('
    ' + value + '
    ') .appendTo(ul); } return listItem; } }, select: function (event, ui) { if (ui.item.disabled) { // suppress disabled items event.preventDefault(); } return false; }, focus: function (event, ui) { if (ui.item.disabled) { // // skip disabled items // let data = $(this).data('ui-autocomplete'); $(data.menu.active).find('div.ui-state-active').removeClass('ui-state-active'); // remove active class if (event.originalEvent.key === 'ArrowDown') { let liBefore = $(data.menu.active).prev(); // li before key pressing let nextLi = data.menu.active; if (!$(nextLi).is(':last-child')) { while ($(nextLi).hasClass('ui-state-disabled')) { // search first not disabled item nextLi = $(nextLi).next(); } if (nextLi.length === 0) { // not found nextLi = liBefore; } } else { // last item nextLi = liBefore; } // setting of active item in jquery-ui autocomplete data.menu.active = nextLi; $(nextLi).find('div').addClass('ui-state-active'); } else { if (event.originalEvent.key === 'ArrowUp') { let liBefore = $(data.menu.active).next(); // li before key pressing let prevLi = data.menu.active; if (!$(prevLi).is(':first-child')) { while ($(prevLi).hasClass('ui-state-disabled')) { // search first not disabled item prevLi = $(prevLi).prev(); } if (prevLi.length === 0) { // not found prevLi = liBefore; } } else { // first item prevLi = liBefore; } // setting of active item in jquery-ui autocomplete data.menu.active = prevLi; $(prevLi).find('div').addClass('ui-state-active'); } } } return false; } });
提交回复
热议问题