Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Tags Input - how to prefill object values

I'm using Bootstrap Tags Input in my form, initalized with following code:

$('#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.

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"}]
like image 959
user1049961 Avatar asked Apr 05 '14 07:04

user1049961


People also ask

How to use Bootstrap tags input?

Use a <select multiple /> as your input element for a tags input, to gain true multivalue support. Instead of a comma separated string, the values will be set in an array. Existing <option /> elements will automatically be set as tags. This makes it also possible to create tags containing a comma.


2 Answers

For anyone needing this:

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});
like image 112
user1049961 Avatar answered Sep 18 '22 23:09

user1049961


Check the document on Method here.

You can use:

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

and

$('input').tagsinput('refresh');
like image 22
Alberto Cerqueira Avatar answered Sep 19 '22 23:09

Alberto Cerqueira