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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:07:29  来源:igfitidea点击:

Bootstrap Tags Input - how to prefill object values

jquerytwitter-bootstraptags

提问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

Check the document on Method here.

此处查看方法文档。

You can use:

您可以使用:

$('input').tagsinput('add', 'some tag');

and

$('input').tagsinput('refresh');

回答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"}]"