javascript - typeahead.js : How to remove value when value not in suggestion

标签 javascript autocomplete typeahead.js

我使用 typeahead.js 作为自动完成文本框。

首先,当我输入并从建议中选择一个值时,文本框会正确设置该值。然后,我输入了一个不在建议中的值,然后按 Tab 键,文本框的值不清除。

当输入值不在建议中时,如何清除文本框的值。

最佳答案

我遇到了同样的情况,我解决这个问题的方法是使用 typeahead.js 的事件。我在 typeahead:select 上记录了一个选择,然后在 typeahead:change 上检查是否做出了选择。如果未进行任何选择,我会将输入重置为原始值。

// Initialize typeahead as ususal
var $myTypeahead = $("#my-typeahead");
$myTypeahead.typeahead(/* Set-up typeahead here */);

// Set up variables to store the selection and the original 
// value.
var selected      = null;
var originalVal   = null;

// When the typeahead becomes active reset these values.
$myTypeahead.on("typeahead:active", function(aEvent) {
   selected       = null;
   originalVal    = $myTypeahead.typeahead("val");
})

// When a suggestion gets selected save that
$myTypeahead.on("typeahead:select", function(aEvent, aSuggestion) {
   selected = aSuggestion;
});

// Once user leaves the component and a change was registered
// check whether or not something was selected. If not reset to
// the original value.
$myTypeahead.on("typeahead:change", function(aEvent, aSuggestion) {
   if (!selected) {
      $myTypeahead.typeahead("val", originalVal);
   }

   // Do something with the selected value here as needed...
});   

关于javascript - typeahead.js : How to remove value when value not in suggestion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24445241/

相关文章:

javascript - 如何在通过 iframe 查看网页时静音

javascript - 当两个元素的高度由其内容定义时,如何确保两个元素在所有屏幕宽度上具有相同的高度?

autocomplete - 如何在 oh-my-zsh 下强制完成文件名?

python - 自定义模块的 Pycharm 类型提示

javascript - 仅使用 typeahead.js 强制有效输入

javascript - Safari:语法错误:使用保留字 'class'

javascript - DataView 和原型(prototype)继承

intellij-idea - IntelliJ : No autocomplete for Kotlin?

jquery - 使用typeahead.js的Rails-400(错误请求)

javascript - Typeahead 调用函数 .val .open .close 等会抛出错误