我是Bootstrap-Twitter框架的新手,我需要使用Bootstrap-typeahead.js进行自动完成,但我也需要获得用户为typeahead选择的值。
这是我的代码:
<input type="text" class="span3" style="margin: 0 auto;"
data-provide="typeahead" data- items="4"
data-source='["Alabama","Alaska"]'>
如何添加侦听器以从typeahead类型中获取所选值并将其传递到函数中?例如,当我使用ExtJs时,我会应用以下结构:
listeners: {
select: function(value){
........
}
}
我怎样才能用排版做类似的事情?
您应该使用"更新程序":
$('#search-box').typeahead({
source: ["foo", "bar"],
updater:function (item) {
//item = selected item
//do your stuff.
//dont forget to return the item to reflect them into input
return item;
}
});
在v3中,twitter引导程序typeahead将被删除,并替换为twitter typeahead(它具有您想要的功能和更多功能)
https://github.com/twitter/typeahead.js
用法如下:
jQuery('#autocomplete-input').on('typeahead:selected', function (e, datum) {
console.log(datum);
});
您可以使用afterSelect
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
感谢p.scheit的回答。让我把它添加到您的解决方案中,该解决方案在用户按下tab键时处理自动完成。
jQuery('#autocomplete-input').on('typeahead:selected', function (e, datum) {
console.log(datum);
}).on('typeahead:autocompleted', function (e, datum) {
console.log(datum);
});
我只需观察元素上的"change"事件就可以实现这一点,Twitter Bootstrap Typeahead会在选择时触发该事件。
var onChange = function(event) {
console.log "Changed: " + event.target.value
};
$('input.typeahead').typeahead({ source: ['test1', 'test2'] });
$('input.typeahead').on('change', onChange);
当用户选择test1时,输出"Changed:test1"。
注意:当用户按下"Enter"时,即使没有找到匹配项,它也会触发事件,所以你必须决定这是否是你想要的。特别是,如果用户输入"te",然后单击"test1",你会得到一个"te"的事件和一个"test1"的事件,你可能想取消它。
(2.0.2版Twitter引导程序Typeahead)
以下是针对选项卡和选定的多事件打开的解决方案:
$('#remote .typeahead').on(
{
'typeahead:selected': function(e, datum) {
console.log(datum);
console.log('selected');
},
'typeahead:autocompleted': function(e, datum) {
console.log(datum);
console.log('tabbed');
}
});
试试这个typeahead分支。它为您提供了一个onselect事件、异步填充等等!
我也遇到了同样的问题。您可以使用此功能创建自定义事件:https://github.com/finom/Functions/tree/master/FunctionCallEvent#why-需要吗(要添加更多事件,您必须了解预编型原型结构)
$('input.typeahead').typeahead({
source: ['test1', 'test2'],
itemSelected: function(e){
---your code here---
}
});