Search code examples
c#jqueryasp.net-mvctag-it

Jquery Tag-IT Allow Comma in the Middle


Ok so here's the thing. We are using the 3rd party control "tag-it" on our controls. JQUERY TAG-IT

Now we have an issue wherein we need to allow the user to paste two word text then put a comma in between. To demonstrate this is the current behavior of the tag-it control:

  1. User paste "text sample"
  2. User puts comma in the middle "text , sample"
  3. Jquery tag-it tags the word as "text sample"

the behavior that i want is this:

  1. User paste "text sample"
  2. User puts comma in the middle "text , sample"
  3. Jquery tag-it tags the words as "text" and "sample"

Is this possible and if yes how could we implement it?


Solution

  • Edit the tag-it.js if you are not using the minified one. Find line 224, and before that line paste this block of code :

    this.tagInput.bind('paste', function (event) {
        // Set short timeout so .val() will have a value
        setTimeout(function () {
            var tagArray = that.tagInput.val().split(/[\n,]+/);
            if (tagArray.length > 1) {
                for (var i = 0; i < tagArray.length; i++) {
                    that.createTag(tagArray[i]);
                }
            }
        }, 100);
    });
    

    So basically what it does is to bind a new paste event and split input by comma, and for separated item, a new tag was created.

    Please refer to this github issue : https://github.com/aehlke/tag-it/issues/301

    You welcome :) ---> You're welcome... Hahahaha.

    QUESTION How about if you're not pasting the values and just manually typed the comma?

    EDIT 2: Another Option

    1. Revert all the changes i done before.

    2. Remove line 244, (event.which === $.ui.keyCode.COMMA && event.shiftKey === false) ||

    This is to allow comma in input

    1. Modify line 270 to check if there is a comma in the input

      that.tagInput.autocomplete('close');
      if ($.trim(that.tagInput.val()).indexOf(',') > -1) {
          var tagArray = that.tagInput.val().split(/[\n,]+/);
          if (tagArray.length > 1) {
              for (var i = 0; i < tagArray.length; i++) {
                  that.createTag($.trim(tagArray[i]));
              }
          }
      }
      else {
          that.createTag(that._cleanedInput());
      }
      

      Explanation: Since we allowed spaces (I assumed) and also allow commas, the only trigger now to create tags is by pressing enter key.

    So for example: Input: "Sample, Text" After I press Enter key, it will be separated into "Sample" and "Text" tags.