Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete should skip disabled element when using keyboard

If you see this Fiddle demo, not done by me, how can I then avoid that the keyboard can go down and choose the disabled element? The mouse is working fine (not being able to select it) but I can go down with the keyboard and select it, resulting in an empty search :-/

The Fiddle demo is from this post, How to disable element in jQuery autocomplete list

jQuery code:

$(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,
    response: function (event, ui) {
        if (ui.content.length > 3) {
            while (ui.content.length > 3) {
                ui.content.pop();
            }
            ui.content.push({
                'label': 'Please narrow down your search',
                    'value': ''
            });
        }
    }
}).data("ui-autocomplete")._renderItem = function (ul, item) {
    return $("<li " + (item.value == '' ? 'class="ui-state-disabled"' : '') + ">")
        .append("<a>" + item.label + "</a>")
        .appendTo(ul);
};
});
like image 263
Beauvais Avatar asked Aug 27 '13 12:08

Beauvais


2 Answers

Autocomplete "knows" to highlight items based on the presense of an <a> inside each li. You can disable keyboard selection of an event by just removing the anchor:

.data("ui-autocomplete")._renderItem = function (ul, item) {
        var $el = $("<li>");
        if (item.value === '') {
            $el.addClass("ui-state-disabled")
               .text(item.label);

        } else {
            $el.append("<a>" + item.label + "</a>");
        }

        return $el.appendTo(ul);
    };

Example: http://jsfiddle.net/m6zvf/12/

like image 155
Andrew Whitaker Avatar answered Oct 20 '22 19:10

Andrew Whitaker


Alternatively to Andrews answer, if you want to preserve the down key wrapping the focus to the first item, you can use the focus event to trigger a mouseenter on the first item upon the unfocusable item coming into focus.

Just add the code below as a focus property

WORKING JS FIDDLE

    focus: function(event, ui){
        var curr = $(event.currentTarget).find('a.ui-state-focus');
        if(curr.parent().hasClass('ui-state-disabled'))
        {
            event.preventDefault(); 
            curr.parent().siblings().first().children('a').mouseenter();  
        }
    }
like image 44
Rooster Avatar answered Oct 20 '22 20:10

Rooster