Search code examples
javascriptjqueryhtmljquery-select2

Pressing Enter is creating the Tag but keeping the Text in Select2


Select2 Version: 4.0.5

Problem: In a multitag (with tags: true or with pre-filled tags) everytime when i hit enter to select the tag, it creates the tag but keeps the text right on side of the new tag, it just disappear if I press another key after. (Happens only with Enter key)

Example:
enter image description here

As you can see, when I type a tag and press Enter, it creates the tag (the expected behavior) but, it keeps the original text in the right side of the new tag...

Is it a normal behavior? Or what should I do?

My Select2 Code:

 var editorTagElement = document.createElement("select");
 editorTagElement.className('myEditor');
 editorTagElement.setAttribute("multiple", "multiple");
 editorTagElement.style.overflow = 'auto';
 editorTagElement.style.fontSize = '13px';

 this.OptionsSelect2 = {};
 this.OptionsSelect2.placeholder = "";
 this.OptionsSelect2.language = ReturnCustomLanguage();
 this.OptionsSelect2.formatNoMatches = function () {
        return '';
 }; 
 this.OptionsSelect2.allowClear = true;
 this.OptionsSelect2.minimumInputLength = 2;
 this.OptionsSelect2.tags = true;
 this.OptionsSelect2.tokenSeparators = [' '];          
 this.OptionsSelect2.createTag = function (params) {              
       var term = $.trim(params.term);
       if (term.length < 2) {
              return null;
       }
       term = term.replace(/ /g, "");         
       return {
            id: term,
            text: term,
            newTag: true
       }
 };
 this.OptionsSelect2.closeOnSelect = false;

 $('.myEditor').select2(this.OptionsSelect2);

After this, I append the editor to body or to another place in my html...


Solution

  • Option closeOnSelect is keeping the value, while it's not an expected behaviour. If you will change closeOnSelect to true (default value, just remove this.OptionsSelect2.closeOnSelect = false; in your code) it will work as you expect.

    To keep popup open after adding a value, you should write a handler similar to suggested in the github issue