28

我正在使用 JQuery UI 自动完成。一切都按预期工作,但是当我使用键盘上的向上/向下键循环时,我注意到文本框按预期填充了列表中的项目,但是当我到达列表末尾并再次按下向下箭头时时间,我输入的原始术语出现了,这基本上允许用户提交该条目。

我的问题:是否有一种简单的方法可以将选择限制为列表中的项目,并从键盘选择中删除输入中的文本?

例如:如果我有一个包含的列表{'Apples (AA)', 'Oranges (AAA)', 'Carrots (A)'},如果用户键入“app”,我将自动选择列表中的第一项(此处为“Apples (AA)”),但如果用户按下向下箭头,“app”再次出现在文本框中。我怎样才能防止这种情况?

谢谢。

4

4 回答 4

43

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("");
                }

            }

        });
于 2012-12-17T15:36:20.150 回答
14

这两个其他答案结合起来效果很好。

此外,您可以使用 event.target 清除文本。当您向多个控件添加自动完成功能或不想在选择器中输入两次(存在可维护性问题)时,这会有所帮助。

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

然而,应该注意的是,即使“焦点”返回 false,向上/向下键仍将选择该值。取消此事件只会取消文本的替换。因此,“j”、“down”、“tab”仍将选择与“j”匹配的第一个项目。它只是不会在控件中显示它。

于 2013-07-11T19:10:57.923 回答
3

"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."

参考

焦点事件:

focus: function(e, ui) {
    return false;
}
于 2012-07-27T04:31:10.453 回答
2

定义一个变量

var inFocus = false; 

将以下事件添加到您的输入中

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

并将 keydown 事件附加到窗口

$(window)
    .keydown(function(e){
        if(e.keyCode == 13 && inFocus) {
            e.preventDefault();
        }
    });
于 2014-06-24T13:12:57.813 回答