Bootstrap tagsinput Can't add objects when itemValue option is not set

PhoebeB picture PhoebeB · Aug 10, 2015 · Viewed 10.3k times · Source

I've seen this question Bootstrap tagsinput add tag with id and value, but the solution is not working for me:

What I'm finding is that in order to get the input box recognising tags that I type in, I either have to have data-role = tagsinput OR call $("input").tagsinput().

eg. This works for recognising tags with no data-role:

$('#meeting-tags').tagsinput();
$('#meeting-tags').tagsinput({
  allowDuplicates: false,
    itemValue: 'id',  // this will be used to set id of tag
    itemText: 'label' // this will be used to set text of tag
});

But this does not:

$('#meeting-tags').tagsinput({
  allowDuplicates: false,
    itemValue: 'id',  // this will be used to set id of tag
    itemText: 'label' // this will be used to set text of tag
});

However, if I want to add items via javascript then it will only work if I neither have data-role nor have an initial call. The error is Can't add objects when itemValue option is not set

eg. this works but now it doesn't recognise tags:

$('#meeting-tags').tagsinput({
      allowDuplicates: false,
        itemValue: 'id',  // this will be used to set id of tag
        itemText: 'label' // this will be used to set text of tag
    });
$('#meeting-tags').tagsinput('add', { id: 'tag id', label: 'tag lable' });

but this does not but now it recognises tags again:

$('#meeting-tags').tagsinput();
$('#meeting-tags').tagsinput({
      allowDuplicates: false,
        itemValue: 'id',  // this will be used to set id of tag
        itemText: 'label' // this will be used to set text of tag
    });
$('#meeting-tags').tagsinput('add', { id: 'tag id', label: 'tag lable' });

There must surely be a way of BOTH being able to recognise tags and add items?

Answer

jasav picture jasav · Feb 26, 2018

I was getting the same issue ("itemValue not set") and checked the plugin and it seems the parameter 'options' in the constructor for the tagsinput is not being set even if you initialize it.

/**
   * Constructor function
   */
  function TagsInput(element, options) {

What I did was put a random string next to the data-role definition in the tag like so, to force it to have that value in the options parameter:

<input type="text" id="mytags" value="" data-role="tagsinput sometext" />

Then did this:

var mytagsinput = $('#mytags');

//initialize
 mytagsinput.tagsinput({
              itemValue: 'id',
                itemText: 'text',
            });

//add my tags object
 mytagsinput.tagsinput('add', { id: 1, text: 'mytext'});   

And it worked for me.