Search code examples
javascriptjqueryhtmltypeahead.jsbootstrap-tags-input

Bootstrap-TagsInput confirmKeys don't work


I can't get the default Bootstrap-TagsInput confirmKeys, namely enter = 13 or comma = 188, to work out of the box. This is true with or without Typeahead.js. Confirm keys allow you to create a tag by clicking that key.

I think the issue is whether or not the tags are strings or objects. If you look at the Tagsinput demo, the "Typeahead" example allows tag creation with the default confirmKeys, enter or comma, but the "Objects as Tags" example right below it does not.

Any idea how to make the confirmKeys work with object tags?


Solution

  • I had to edited Bootstrap-tagsinput library to make this work.

    Here's what I added/commented out in the library:

     //self.options.freeInput = false; //notice commented out
    
    //... (lots of lines between)
    
    if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) {
        // Only attempt to add a tag if there is data in the field
    
        if (text.length !== 0) {
           //<<<<< BEGIN code block added
           //self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text); //notice commented out
    
           var item2 = self.$input.val();
           if (self.objectItems) {
             var beforeFreeInputItemAdd = $.Event('beforeFreeInputItemAdd', { item: item2, cancel: true });
             self.$element.trigger(beforeFreeInputItemAdd);
             if (beforeFreeInputItemAdd.cancel)
               return;
    
             item2 = beforeFreeInputItemAdd.item;
           }
    
           self.add(item2);
           self.$input.val(''); 
           //  $input.val(''); //>>>>>> END code block added
        }
    
    }
    

    And then to anywhere in one's codebase that wants to make use of this library modification I added this:

    var id_increment = 1;
    $("#my-tagsinput-field").on('beforeFreeInputItemAdd', function(event) {
    
        event.item = {'name': event.item, 'id': 'new-'+id_increment};
        event.cancel = false;
        id_increment++;
    
    });