JQuery自动完成:如何强制从列表中选择(键盘)

Ali*_*i B 25 jquery jquery-ui jquery-ui-autocomplete

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

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

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

谢谢.

Sau*_*abh 39

对于强制选择,您可以使用自动填充的"更改"事件

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

            }

        });
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案的问题在于,如果有人在字段中键入非法值然后按Enter键,则表单将以非法值提交.仍在努力寻找优雅的解决方案. (3认同)

Ric*_*ard 11

这两个组合的其他答案都很有效.

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

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

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


Ric*_*ann 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;
}
Run Code Online (Sandbox Code Playgroud)