jquerytagspasteeventtriggerjquery-tags-input

Jquery tagsinput not creating tags automatically on pasting input


I'm using jquery.tagsinput and would like to be able to paste a list of email addresses separated by comma or space. Using something like this https://github.com/xoxco/jQuery-Tags-Input/issues/22 but it doesn't add them until I press Enter - Tried triggering keypress Enter event but it doesn't work. No luck with blur event either (shown below). Any ideas?

The Flat-UI tags are based on this library and I'm trying to achieve a very similar behaviour.

var tidyTags = function(e) {
  var tags = (e.tags).split(/[ ,]+/);
  var target = $(e.target);

  for (var i = 0, z = tags.length; i<z; i++) {
      var tag = $.trim(tags[i]);
      if (!target.tagExist(tag)) {
          target.addTag(tag);
      }
  }
  $('#' + target[0].id + '_tag').trigger('focus');

  //This doesn't work.
  target.blur();

};

$("#tagsinput").tagsInput({
    onAddTag : function(tag){
      if(tag.indexOf(',') > 0) {
          tidyTags({target: '#tagsinput', tags : tag});
      }
    },
});

Solution

  • Ok finally figured out the solution:

    DEMO HERE

    Just add a listener to your textbox while pasting and do not set onAddTag during initialization and just give it a simple call as below:

    $("#tagsinput").tagsInput();//Initialization
    
    $("#tagsinput_tag").on('paste',function(e){
        var element=this;
        setTimeout(function () {
            var text = $(element).val();
            var target=$("#tagsinput");
            var tags = (text).split(/[ ,]+/);
            for (var i = 0, z = tags.length; i<z; i++) {
                  var tag = $.trim(tags[i]);
                  if (!target.tagExist(tag)) {
                        target.addTag(tag);
                  }
                  else
                  {
                      $("#tagsinput_tag").val('');
                  }
             }
        }, 0);
    });
    

    Some points to note:

    • paste method will only fire if text is selected in Firefox
    • tagsinput will hide your #tagsinput textbox and adds its own input textbox and thus you need to call paste event on #tagsinput_tag textbox and the structure of the element will be as shown in below image:Structure image