我正在使用bootstrap typeahead.js功能来进行“状态”查找的自动完成功能。如何才能最好地阻止个人在提交表格之前键入所有内容(而不是成功挑选阿拉斯加州)?
答案 0 :(得分:1)
Typeahead.js目前不支持此行为
您可以使用更适合受限选项的其他库,例如Select2
但是我有Typeahead的工作分支支持这个。
请参阅此处的JQuery示例页面:
https://github.com/Svakinn/typeahead.js/blob/typeaheadSimple/Examples.md
答案 1 :(得分:0)
根据您的要求,您可以仅从有效选项中进行选择,并清除所有无效输入。
首先创建一个自定义source
来跟踪搜索结果:
var sync = false;
var current_results = [];
var current_q = '';
var selected_val = '';
function search(q, sync) {
current_q = q;
window.sync = sync;
engine.search(q, cust_sync);
}
function cust_sync(datums) {
current_results = datums;
sync(datums);
}
$('#typeahead').typeahead(
{
highlight: true,
minLength: 0
},
{
source: search // custom search engine
}
);
然后绑定select
和change
事件处理程序。
$('#typeahead').bind('typeahead:change', function(ev) {
var current_val = $('#typeahead').val();
// user moved cursor out of input without selecting from the menu
if(current_val != selected_val){
// current query has search results
if(current_results.length)
// change input to the first valid search result
$('#typeahead').typeahead('val', current_results[0].name);
// no results for this query - clear input
else
$('#typeahead').typeahead('val', '');
}
});
$('#typeahead').bind('typeahead:select', function(ev, suggestion) {
selected_val = $('#typeahead').val(); // keep track of a selected value
});