我正在使用Bootstra2.1.1和jQuery 1.8.1,并尝试使用Typeahead的功能。
我尝试显示一个标签,并像标准<select />一样使用id。
以下是我的提前输入初始化:
$(':input.autocomplete').typeahead({
source: function (query, process) {
$('#autocompleteForm .query').val(query);
return $.get(
$('#autocompleteForm').attr('action')
, $('#autocompleteForm').serialize()
, function (data) {
return process(data);
}
);
}
});这是我要发送的JSON
[{"id":1,"label":"machin"},{"id":2,"label":"truc"}]如何告诉process()显示我的标签并将所选ID存储在另一个隐藏字段中?
发布于 2012-11-07 22:13:45
这里有一个很好的教程来解释如何做到这一点:http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/ (如果它还没有反映在文章的主要部分,请阅读我在该页面上的评论)。
基于该教程和您提供的JSON,您可以这样做:
$(':input.autocomplete').typeahead({
source: function(query, process) {
objects = [];
map = {};
var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
},
updater: function(item) {
$('hiddenInputElement').val(map[item].id);
return item;
}
}); 发布于 2014-02-14 10:00:10
在Twitter (https://github.com/twitter/typeahead.js)的0.10.1版本中,Id / Label是本地支持的:
$('input[name=address]').typeahead({
hint: false
}, {
source: function (query, cb) {
$.ajax({
url: '/api/addresses?q=' + encodeURIComponent(query),
dataType: 'json',
cache: false,
type: 'GET',
success: function (response, textStatus, jqXHR) {
cb(response.data);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
},
name: 'addresses',
displayKey: 'text'
}).on('typeahead:selected', function (e, suggestion, name) {
window.location.href = '/' + suggestion.id;
});如果是上面的例子,我将把一个对象数组传递给源回调(cb)。通过指定displayKey:“text”,我告诉库使用“text”属性进行自动提示。当调用'typeahead:select‘回调时,传入的第二个参数(建议)包含被选中的对象。
发布于 2013-04-21 23:48:36
来澄清我在评论中说的话。如果您想要在同一个页面上多个类型的ahead,您需要在一个函数中定义每个类型,并为它们创建一个单独的映射变量。
function initFromField() {
var map;
$('#from:input.autocomplete').typeahead({
source: function(query, process) {
map = {};
var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
objects = constructMap(data, map);
process(objects);
},
updater: function(item) {
$('#hidden-from-input').val(map[item].id);
return item;
}
});
}
function initToField() {
var map;
$('#to:input.autocomplete').typeahead({
source: function(query, process) {
objects = [];
map = {};
var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
objects = constructMap(data, map);
process(objects);
},
updater: function(item) {
$('#hidden-to-input').val(map[item].id);
return item;
}
});
}
function constructMap(data, map) {
var objects = [];
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
return objects;
}
$(function initFields() {
initFromField();
initToField();
});请注意,我是如何在两个字段初始化函数中限定map变量的范围的。这一点很重要,它确保两个输入字段不使用相同的map变量。
https://stackoverflow.com/questions/12389948
复制相似问题