Set pipe as the delimiter for Select2

2019-09-11 18:41发布

问题:

I have one multiple select dropdown, and I want to set pipe (|) as the delimiter.

For example, when a user selects multiple options (like Option1, Option2 and Option3) then it should separate (delimit) the values like this:

Option1|Option2|Option3

Below is my code:

$("#granttype").select2({ allowClear: true, tags: true, tokenSeparators: ['|'] });

I wrote this in the $document.ready() function.

回答1:

You have to use option tokenSeparators

$("#selectbox").select2({
  tags: true,
  tokenSeparators: ['|']
})


回答2:

incase your problem is not resolved yet, here is the answer! On older versions of select2 you got to use 'separator' instead of 'tokenSeparators, like this.

jQuery('selector').select2({
                            separator: ";",
                            allowClear:true,
                            ...
                            ...
                               });

Although as a fall back if you're not sure about the version of select2, the preferred way is to keep both the options, like this.

jQuery('selector').select2({
                            tokenSeparators: [';'],
                            separator: ";",
                            allowClear:true,
                            ...
                            ...
                               });


回答3:

For who still looking this,
This is script that working for me :

$(element).select2({
  tags: [],
  separator: "|"
});

The "tags: []," must be included, otherwise it give errors
Hope it help