Ahmed Kato
Ahmed Kato

Reputation: 1707

Bootstrap tags input not working with jquery

I am using Bootstrap tags input to make tags inside text input,in the documentation:

Just add data-role="tagsinput" to your input field to automatically change it to a tags input field.

But when using jquery before function:

$('#addrun').click(function () {
            $('#addrun').before('<input type="text" value="Amsterdam,Washington,Sydney,Beijing" data-role="tagsinput" />');    
        });

it is displayed like any text input with text inside and no tags.

any help ??

Upvotes: 9

Views: 20377

Answers (2)

MackieeE
MackieeE

Reputation: 11862

Bootstrap is run at page load as an self-executing function. By adding a new element to the DOM - By that time, bootstrap-tagsinput.js wouldn't know anything about it. So you'll have to Initialise it after adding it to the DOM document via JavaScript.

To refresh input tags (Bootstrap Tagsinput Docs):

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

So for you, you'd need to:

/** 
 * On <div id="addrun"> on click,
 * pre-apend it with an new Input
 *
 * Then refresh Bootstrap. 
**/
$('#addrun').click(function(){

     $('#addrun').before(
         '<input type="text" '+
         'value="Amsterdam,Washington,Sydney,Beijing" '+
         'data-role="tagsinput" />'
     ); 

     //Now run bootstrap.js to re-search
     //new data-* elements
     $('input').tagsinput('refresh');   
});

Hope that helps! Although, the above $('input') will refresh every <input> tag in the whole document, so you could instead give the prepended <input> tag an .class or an #ID for quicker access =)

Update:

As koala_dev did correctly mention within the comments, you probably wouldn't need to initialise it via $('selector').tagsinput('refresh') but rather just:

     $('#selecor').tagsinput();

.tagsinput('refresh') would normally be actioned on an .tagsinput() input that's already initialised with new options given.

Upvotes: 14

Khademul Basher
Khademul Basher

Reputation: 127

I made it working following ways. It was showing problem $(..).tagsinput() was not found and I could now update the tags with new values.

I removed first and last line from file bootstrap-tagsinput.js, that is '(function ($) {' and '})(window.jQuery)'.

And called the below two lines where tags was required to display and update.

$("input[data-role=tagsinput]").tagsinput('removeAll');
$("input[data-role=tagsinput]").tagsinput('add', 'New Value');

Upvotes: 8

Related Questions