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

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

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

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

谢谢。

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

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

这两个其他答案的组合效果很好。

此外,您可以使用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”的第一个项目。 它只是不会在控件中显示它。

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

定义变量

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