Search code examples
javascripttwitter-bootstrapbootstrap-tags-input

Calling "add" method from bootstrap-tag library


So I am using a library called bootstrap-tag (not to be confused with bootstrap-tags <-plural). Here is its repository: https://github.com/fdeschenes/bootstrap-tag

I am trying to build the value that the tag will have from other input fields and then from a click of a button, add that tag to the tag-input field.

enter image description here

I first tried to see if I could access the element's prototype and get the add method from there. But I could only ever get the prototype of a jquery element. Only reason I'm not including code is because I am using Ember.js and don't want that to possibly complicate the actual problem I am having. If it is beneficial for me to include code, let me know and I'll add it to the question.

The tag-input field works perfectly when typing inside of it. How do I build the value from outside of the field and add a tag?

Also the add method I am aiming to use is on this line in the 3rd party library: https://github.com/fdeschenes/bootstrap-tag/blob/master/js/bootstrap-tag.js#L136


Solution

  • This library doesn't provide an API for this.. But you can hack it easily ;)

    <input id="test-input" />
    
    var tags = new $.fn.tag.Constructor(document.getElementById('test-input'), {});
    tags.add('Hack');
    tags.add('it');
    tags.add('easily');
    

    OR you can do this:

    var tagsElement = $('.tags-input').tag(options);
    
    addTagToElement(tagsElement, 'Whatever');   
    
    function addTagToElement(el, newTag) {
       var e = $.Event('keydown');
       e.keyCode = 13;
       el.next().val(newTag);
       el.next().trigger(e)
    }
    

    This library creates a placeholder input next to the first defined, and listen to the keydown even.. So the addTagToElement snippet simply simulates this..