【发布时间】:2012-03-21 19:23:41
【问题描述】:
我想在用户选择一个值之后使用 twitter bootstrap Typeahead 运行 Javascript 函数。
我搜索一些诸如选定事件之类的东西。
【问题讨论】:
-
真正的答案不是被选中的那个……:(
标签: javascript jquery twitter-bootstrap events jquery-events
我想在用户选择一个值之后使用 twitter bootstrap Typeahead 运行 Javascript 函数。
我搜索一些诸如选定事件之类的东西。
【问题讨论】:
标签: javascript jquery twitter-bootstrap events jquery-events
我第一次在这里发布答案(虽然很多次我在这里找到了答案),所以这是我的贡献,希望它有所帮助。您应该能够检测到变化 - 试试这个:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
【讨论】:
我创建了一个包含该功能的扩展。
【讨论】:
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
【讨论】:
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
【讨论】:
关于 typeahead 的作用方式的解释,你想在这里做什么,以下面的代码示例为例:
HTML 输入框:
<input type="text" id="my-input-field" value="" />
JavaScript 代码块:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
解释:
$('#my-input-field').typeahead(
source: 选项以获取 JSON 列表并将其显示给用户。updater: 选项。 请注意,它尚未使用所选值更新文本字段。item 变量抓取选定的项目,然后用它做您想做的事情,例如myOwnFunction(item)。$fld 的引用的示例,以防您想对其进行操作。 请注意,您不能使用 $(this) 引用该字段。updater: 选项中包含return item; 行,以便输入字段实际上使用item 变量进行更新。【讨论】:
根据他们的documentation,处理selected 事件的正确方法是使用此事件处理程序:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
【讨论】:
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
【讨论】:
对我有用的如下:
$('#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();
}
});
【讨论】: