jQuery Bootstrap 标签输入 - 如何预填充对象值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22878116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bootstrap Tags Input - how to prefill object values
提问by user1049961
I'm using Bootstrap Tags Input in my form, initalized with following code:
我在我的表单中使用 Bootstrap 标签输入,用以下代码初始化:
$('#looking_for_job_titles').tagsinput({
itemValue: 'id',
itemText: 'name'
});
// TypeAhead.js
var job_scopes = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.value);
},queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 100,
remote: {
url: 'http://www.domain.com/json.php?action=job_title&q=%QUERY'
}
});
job_scopes.initialize();
$('#looking_for_job_titles').tagsinput('input').typeahead({
itemValue: 'name'
},
{
name: 'job_scope',
displayKey: 'name',
source: job_scopes.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'no results found',
'</div>'
].join('\n'),
suggestion: function(data){
return '<p>'+ data.industry +'> <strong>' + data.name + '</strong></p>';
}
},
engine: Hogan
}).bind('typeahead:selected', $.proxy(function (obj, datum) {
this.tagsinput('add', datum);
}, $('#looking_for_job_titles')));
This works fine, and returns comma separated list of ids, which I save into db.
这工作正常,并返回逗号分隔的 id 列表,我将其保存到 db 中。
My problem is how to prefill the object values back into the input field on page refresh? The object looks like:
我的问题是如何在页面刷新时将对象值预填回输入字段?该对象看起来像:
[{"id":"80001","name":"Account Manager"},{"id":"80251","name":"Projektant"}]
回答by user1049961
For anyone needing this:
对于任何需要这个的人:
$.each(obj, function(index, value) {
$('#looking_for_job_titles').tagsinput('add', value);
console.log(value);
});
回答by Alberto Cerqueira
回答by Tomá? Tibensky
it should be simple, fill value=""
attribute of that input, but without javascript.
If you do this in the correct format value="1,2,3"
it will work
它应该很简单,填充value=""
该输入的属性,但没有 javascript。如果您以正确的格式执行此操作,value="1,2,3"
它将起作用
回答by Tomá? Tibensky
so it will be
所以它会
value=" [{"id":"80001","name":"Account Manager"},{"id":"80251","name":"Projektant"}]"