Networker Networker - 1 year ago 144
jQuery Question

How to add default value to bootstrap tag select input?

I'm using Bootstrap tag plugin and I successfully add some tags to it using this code:

$(function () {
var data = [{"id":"1","value":"painting-works"},{"id":"2","value":"plumbing-works"},{"id":"3","value":"programming"}];
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data
});
states.initialize();
$("#tags").tagsinput({
itemValue: 'id',
itemText: 'value',
allowDuplicates: false,
maxTags: 1,
typeaheadjs: {
name: "states",
displayKey: 'value',
source: states.ttAdapter(),
},
freeInput: true
});
});




and the input element is

<select placeholder="" class="bootstrap-tagsinput" id="tags"></select>


the tags are added successfully
enter image description here

but what I want is to add a default value to the input element when the page is loaded like this
enter image description here

I have tried this code

$('#tags').tagsinput('add', 'new');


but it only adds a new tag
and I tried to use jQuery

$('#tags').val("painting-works");


but it didn't work, what should I do?

Answer Source

Notice that you are using array of objects as the data, so you need to pass one of the object to tagsInput on page load

$('#tags').tagsinput('add', {"id":"1","value":"painting-works"});  

here is the jsfiddle with solution

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download