Guide
Tags and creating options
Tags
createSelect(document.querySelector('#tags'), {
tags: true,
name: 'tags',
separators: ['Enter', ',', 'Tab'],
options: existingTags, // suggestions, if you have them
});
Typing and pressing Enter, comma or Tab turns the text into a chip. So does pasting
design, research, urgent. Backspace on an empty field removes the last chip — it never turns the
field back into raw text, which is select2's most-reacted bug.
The value is an array of strings; with a <select> the widget makes it multiple and adds the
<option>s, so the form posts tags[] as it would natively.
Creating options in a normal select
createSelect(select, {
creatable: true,
onCreate: (option) => console.log('new', option),
});
The typed text appears as the last row — Add “Atlantis” — only when it doesn't already exist. It is a
row like any other, so Enter takes it and the keyboard never has to leave the list.
Shape it yourself to add a prefix, an id or a flag:
createSelect(select, {
creatable: (query) => (query.length < 2 ? null : { value: `new:${query}`, label: query, data: { isNew: true } }),
});
Returning null refuses the text — a validation rule ("at least two characters", "letters only",
"must be an email") with no extra UI.
Limits
maxSelected stops at a number and announces it. hideSelected (on by default when multiple) takes
chosen values out of the list so long lists stay short.