Bootstrap tagsinput add tag with id and value

2020-02-28 02:57发布

问题:

I am using Bootstrap Tags Input

I am trying to add tags dynamically.

$('.div-tag').tagsinput('add', 'vino');

The above code works fine, but when I try the following code:

$('.div-tag').tagsinput('add', { id: 1, text: 'some tag' });

I get the error:

Uncaught Can't add objects when itemValue option is not set

Please help me to add tag with id and value.

回答1:

initialize tags input like

 $('.div-tag').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
    });

To add dynamic tag

$('.div-tag').tagsinput('add', { id: 'tag id', label: 'tag lable' });

That's it;



回答2:

I spent few hours to find out, that above working only when data-role="tagsinput" is removed from your

<input class="div-tag" />


回答3:

This library is broken, don't bother. The accepted answer doesn't work on version 0.8. After 1h of trying several things, I suggest to switch to another library, I used tagEditor , where everything worked on the 1st try.



回答4:

There is nothing wrong with the library, but when you get this error it means there is a problem with the method initilization.

Try to do it when the page is ready like so:

$(document).ready(function(){
   $('#myInput').tagsinput({
       allowDuplicates: false,
       itemValue: 'id',
       itemText: 'label'
    });
});

$(".someButton").click(function(){
   $('#myInput').tagsinput('add', {id:1, label:"blah blah"});
}


回答5:

Please try like this:

<div data-src="<?php echo get_template_directory_uri(); ?>/images/index_slide01.jpg">
    <div class="fadeIn camera_caption">
        <h2 class="text_1 color_1">Solutions that you need!</h2>
        <a class="btn_1" href="#">More info</a>
    </div>
</div>