Twitter引导程序Typeahead-Id&标签
Twitter Bootstrap Typeahead - Id & Label
我正在使用Bootstrap 2.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存储在另一个隐藏字段中?
这里有一个很棒的教程,解释了如何做到这一点: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;
}
});
自Twitter Typeahead 0.10.1版本起(https://github.com/twitter/typeahead.js),本机支持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"回调时,传入的第二个参数(建议)包含所选的对象。
澄清我在评论中所说的内容。如果你想在同一页上有多个类型的ahead,你需要在一个函数中定义每个类型的aheads,并为它们创建一个单独的映射变量。
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();
});
请注意我是如何在两个字段初始化函数中确定映射变量的范围的。这一点很重要,它可以确保两个输入字段不使用相同的映射变量。
我自己也一直在努力解决这个问题,以下是我为以下类型的数据想出的解决方案:
[{'id':an_id, 'name':a_name}]
曾:
$("#memberSearch").typeahead({
source: function (query, process) {
var $this = this //get a reference to the typeahead object
return $.get('/getSwimmerListJSON',function(data){
var options = [];
$this["map"] = {}; //replace any existing map attr with an empty object
$.each(data,function (i,val){
options.push(val.name);
$this.map[val.name] = val.id; //keep reference from name -> id
});
return process(options);
});
},
updater: function (item) {
console.log(this.map[item],item); //access it here
}
});
我在其中一些解决方案中看到的问题是,在输入框的每个keyup事件上都会重复调用source
函数。也就是说,数组正在构建中,并在每个keyup事件上循环。
这是没有必要的。使用闭包,您只能处理数据一次,并在source
函数中维护对它的引用。此外,以下解决方案解决了@Gerbus解决方案的全局命名空间问题,还允许您在用户选择某个内容后(例如,从列表中删除该项)使用数据数组。
// Setup the auto-complete box of users
var setupUserAcUi = function(data) {
var objects = [];
var map = {};
$.each(data, function(i, object) {
map[object.name] = object;
objects.push(object.name);
});
// The declaration of the source and updater functions, and the fact they
// are referencing variables outside their scope, creates a closure
$("#splitter-findusers").typeahead({
source: function(query, process) {
process(objects);
},
updater: function(item) {
var mapItem = map[item];
objects.splice( $.inArray(item, objects), 1 ); // Remove from list
// Perform any other actions
}
});
};
// `data` can be an array that you define,
// or you could pass `setupUserAcUi` as the callback to a jQuery.ajax() call
// (which is actually how I am using it) which returns an array
setupUserAcUi(data);
选择的答案有点像破解。我一直在寻找同样的东西,这种方法效果很好:
https://github.com/twbs/bootstrap/pull/3682
它保留了两个数组,一个用于typeahead显示的名称,另一个用于提取名称的对象。当选择其中一个选项时,它会使用名称来查找其来源的对象。
这里是一个封装的解决方案。此解决方案允许您在同一页面上进行多个排版。
这是#13279176 Gerbus答案的修改版本。
$('.make-me-typeahead').typeahead({
source: function (query) {
var self = this;
self.map = {};
var items = [];
var data = [
{"id": 1, "label": "machin"},
{"id": 2, "label": "truc"}
];
$.each(data, function (i, item) {
self.map[item.label] = item;
items.push(item.label)
});
return items;
},
updater: function (item) {
var selectedItem = this.map[item];
this.$element.data('selected', selectedItem);
return item;
}
});
现在,当您需要获得当前所选项目的密钥时,您只需要执行$('.make-me-typeahead').data('selected')
这只是实现Pierref函数的另一种方法。
var separator = "####";
$("'.autocomplete'").typeahead({
minLength: 3,
source: function (query, process) {
var config = {
type: 'POST',
url: 'Requests/AJAX.PHP', //Change it
cache: 'false',
data: {
query: query
},
dataType: 'json'
};
config.beforeSend = function () {
//TODO : loading gif
};
config.error = function (json) {
if (json.error) {
alert(json.error);
}
};
config.success = function (json) {
if (json.error) {
alert(json.error);
}
var data = [];
for (var i = 0; i < json.data.length; i++) {
data.push(json.data[i].id + separator + json.data[i].name);
}
process(data);
};
$.ajax(config);
},
highlighter: function (item) {
var parts = item.split(separator);
parts.shift();
return parts.join(separator);
},
updater: function (item) {
var parts = item.split(separator);
$('.autocomplete').val(parts.shift());
return parts.join(separador);
}
});
所选答案不涉及非唯一标签(例如人名)。我正在使用以下保持默认荧光笔格式:
var callback = function(id) {
console.log(id);
};
$('.typeahead',this.el).typeahead({
source: function (query, process) {
var sourceData = [
{id:"abc",label:"Option 1"},
{id:"hfv",label:"Option 2"},
{id:"jkf",label:"Option 3"},
{id:"ds",label:"Option 4"},
{id:"dsfd",label:"Option 5"},
];
var concatSourceData = _.map(sourceData,function(item){
return item.id + "|" + item.label;
});
process(concatSourceData);
},
matcher : function(item) {
return this.__proto__.matcher.call(this,item.split("|")[1]);
},
highlighter: function(item) {
return this.__proto__.highlighter.call(this,item.split("|")[1]);
},
updater: function(item) {
var itemArray = item.split("|");
callback(itemArray[0]);
return this.__proto__.updater.call(this,itemArray[1]);
}
});
我制作了一个Angular 2指令,typeahead Angular 2,它完全符合您的要求,并处理非唯一标签的情况。你可以先打字。
此指令处理具有多个属性和处理标签不唯一的情况。它基本上收到4参数:
@Input() name;
//用于预编的名称@Input() objectsDataSet;
//对象的数据集,它可以是任何类型的对象@Input() handleFunction;
//选择对象时调用的回调函数,您可以传递对象或任何您想要的此功能@Input() labelAtt;
//标签属性(object[labelAtt]
显示给用户,必须是字符串)示例:
<input type="text" class="form-control" placeholder="Name..." typeaheadautocomplete [objectsDataSet]="clientList" [labelAtt]="'Firstname'" [name]="'clients'" [handleFunction]="logClient">
正如您所看到的:
clientList
是一个"客户端"对象数组,让我们比如{"Fistname":"Billel","Lastname":"Guerfa",....}
,我们使用自动完成列表的Firstname属性。此处收到logClient
客户端对象并显示它。依赖项:
只需在index.html级别声明typeahead脚本。
- 预先打印:https://twitter.github.io/typeahead.js/
请参阅:https://github.com/BillelGuerfa/typeahead-angular2/
- 在<页眉>标签
- jquery点击函数select&取消选择
- Ckeditor-plugin:插入虚假元素add不情愿<p>标签前后
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- Angular js-返回一个包含类似
- 一点javascript元编程&可链接的设置器
- Twitter引导程序Typeahead-Id&标签
- 用于x轴的Dojo图表选择性标签&网格
- 删除 p标签之间
- 在每个条形图的中间添加文本标签&鼠标悬停事件
- 谷歌标签管理器添加&instrad of just&转换为脚本src
- gRaphael折线图:用JSON数据填充弹出标签而不是x&y坐标
- 钛:标签&选项卡组-自定义;backgroundImage”;
- 在带有id&标签
- jQuery针对特定ul&李标签
- javascript替换®和html标签
- JavaScript DOM api能得到属性&的原始大小写吗?标签的名字
- 使用Switch语句来更改值&根据预先存在的值为文本输入插入标签
- 防止降价处理器转换“>"至“>"在<脚本>标签
- 谷歌图表时间线:问题与着色&条形标签