JQuery autocomplete: how to force selection from list (keyboard)

你离开我真会死。 提交于 2019-12-03 04:31:07

for force selection, you can use "change" event of Autocomplete

        var availableTags = [
            "ActionScript",
            "AppleScript"
        ];
        $("#tags").autocomplete({
            source: availableTags,
            change: function (event, ui) {
                if(!ui.item){
                    //http://api.jqueryui.com/autocomplete/#event-change -
                    // The item selected from the menu, if any. Otherwise the property is null
                    //so clear the item for force selection
                    $("#tags").val("");
                }

            }

        });

Both of these other answers in combination work well.

Also, you can use the event.target to clear the text. This helps when you are adding auto-complete to multiple controls or when you don't want to type in the selector twice (maintainability issues there).

$(".category").autocomplete({
    source: availableTags,
    change: function (event, ui) {
        if(!ui.item){
            $(event.target).val("");
        }
    }, 
    focus: function (event, ui) {
        return false;
    }
});

It should be noted, however, that the even though the "focus" returns false, the up/down keys will still select the value. Cancelling this event only cancels the replacing of the text. So, "j", "down", "tab" will still select the first item that matches "j". It just won't show it in the control.

"Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused."

reference

On focus event:

focus: function(e, ui) {
    return false;
}

Define a variable

var inFocus = false; 

Add the following events to your input

.on('focus', function() {
    inFocus = true;
})
.on('blur', function() {
    inFocus = false;
})

And attach a keydown event to the window

$(window)
    .keydown(function(e){
        if(e.keyCode == 13 && inFocus) {
            e.preventDefault();
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!