Add "OR" text to select 2


#1

Hi,

I currently have this:


                $('#' + vueComponent.name).select2({
                    tags: true,
                   templateSelection: formatOption
                });


 function formatOption (option) {

                if (!option.id) {
                    return option.text;
                }

                var $option = $(
                    '<span>' + option.element.value +  ' </span><strong>OR</strong>'
                );
                return $option;
            };

OR

Ideally, I would like the OR to separate the tags, any idea how I can do this?

Thanks,

Mick


#2

If screen reader accessibility is not a concern (i.e., the “OR” might not be announced by the screen reader), you could insert the “OR” text as the content of the li.select2-selection__choice::before element. You just need to reserve space in the left margin for the generated text, and you need to exclude the first selection. The following CSS does the trick:

.select2-container--default li.select2-selection__choice:nth-of-type(n+2) {
    margin-left: 2em;
    position: relative;
}
.select2-container--default li.select2-selection__choice:nth-of-type(n+2)::before {
    content: " OR ";
    position: absolute;
    left: -2em;
}

The result looks like this: