A vanilla, lightweight (~20kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.
The use of import of css/scss is supported from webpack.
In .scss: `scss @import "choices.js/src/styles/choices"; `
In .js/.ts: `javascript import "choices.js/public/assets/styles/choices.css"; `
Setup
Note: If you pass a selector which targets multiple elements, the first matching element will be used. Versions prior to 8.x.x would return multiple Choices instances.
`js // Pass single element const element = document.querySelector('.js-choice'); const choices = new Choices(element);
// Pass reference const choices = new Choices('[data-trigger]'); const choices = new Choices('.js-choice');
// Pass jQuery element const choices = new Choices($('.js-choice')[0]);
| Word | Definition | | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Choice | A choice is a value a user can select. A choice would be equivalent to the element within a select input. | | Group | A group is a collection of choices. A group should be seen as equivalent to a element within a select input. | | Item | An item is an inputted value (text input) or a selected choice (select element). In the context of a select element, an item is equivalent to a selected option element: whereas in the context of a text input an item is equivalent to |
Input Types
Choices works with the following input types, referenced in the documentation as noted.
| HTML Element | Documentation "Input Type" | | -------------------------------------------------------------------------------------------------------| -------------------------- | | | text | |
Usage: The amount of choices to be rendered within the dropdown list ("-1" indicates no limit). This is useful if you have a lot of choices where it is easier for a user to use the search area to find a choice.
$3
Type: NumberDefault:-1
Input types affected: text, select-multiple
Usage: The amount of items a user can input/select ("-1" indicates no limit).
$3
Type: Boolean | 'auto' Default:auto
Input types affected: select-one, select-multiple
Usage: Control how the dropdown closes after making a selection for select-one or select-multiple. - 'auto' defaults based on backing-element type: - select-one: true - select-multiple: false
$3
Type: BooleanDefault:false
Input types affected: select-one, select-multiple
Usage: Make select-multiple with a max item count of 1 work similar to select-one does. Selecting an item will auto-close the dropdown and swap any existing item for the just selected choice. If applied to a select-one, it functions as above and not the standard select-one.
$3
Type: BooleanDefault:false
Input types affected:
select-multiple, select-one
Usage: Whether a user can add choices dynamically.
Note:
addItems must also be true
$3
Type:
BooleanDefault:true
Input types affected:
text
Usage: Whether a user can add items.
$3
Type:
BooleanDefault:true
Input types affected:
text, select-multiple
Usage: Whether a user can remove items.
$3
Type:
BooleanDefault:false
Input types affected:
text, select-one, select-multiple
Usage: Whether each item should have a remove button.
$3
Type:
BooleanDefault:false
Input types affected:
text, select-one, select-multiple
Usage: Align item remove button left vs right
$3
Type:
BooleanDefault:false
Input types affected:
text
Usage: Whether a user can edit items. An item's value can be edited by pressing the backspace.
$3
Type:
BooleanDefault:false
Input types affected:
text, select-one, select-multiple
Usage: Whether HTML should be rendered in all Choices elements. If
false, all elements (placeholder, items, etc.) will be treated as plain text. If true, this can be used to perform XSS scripting attacks if you load choices from a remote source.
$3
Type:
BooleanDefault:false
Input types affected:
text, select-one, select-multiple
Usage: Whether HTML should be escaped on input when
addItems or addChoices is true. If false, user input will be treated as plain text. If true, this can be used to perform XSS scripting attacks if you load choices from a remote source.
$3
Type:
BooleanDefault:true
Input types affected:
text
Usage: Whether duplicate inputted/chosen items are allowed
$3
Type:
StringDefault:,
Input types affected:
text
Usage: What divides each value. The default delimiter separates each value with a comma:
"Value 1, Value 2, Value 3".
$3
Type:
BooleanDefault:true
Input types affected:
text, select-multiple
Usage: Whether a user can paste into the input.
$3
Type:
BooleanDefault:true
Input types affected:
select-one, select-multiple
Usage: Whether a search area should be shown.
$3
Type:
BooleanDefault:true
Input types affected:
select-one
Usage: Whether choices should be filtered by input or not. If
false, the search event will still emit, but choices will not be filtered.
$3
Type:
Array/StringDefault:['label', 'value']
Input types affected:
select-one, select-multiple
Usage: Specify which fields should be used when a user is searching. If you have added custom properties to your choices, you can add these values thus:
['label', 'value', 'customProperties.example'].
$3
Type:
NumberDefault:1
Input types affected:
select-one, select-multiple
Usage: The minimum length a search value should be before choices are searched.
$3
Type:
NumberDefault:4
Input types affected:
select-one, select-multiple
Usage: The maximum amount of search results to show ("-1" indicates no limit).
$3
Type: Document Element Default: null
Input types affected:
select-one, select-multiple
Usage: You can pass along the shadowRoot from your application like so.
`js var shadowRoot = document .getElementById('wrapper') .attachShadow({ mode: 'open' }); ... var el = shadowRoot.querySelector(...); var choices = new Choices(el, { shadowRoot: shadowRoot, }); `
$3
Type:
StringDefault:auto
Input types affected:
select-one, select-multiple
Usage: Whether the dropdown should appear above (
top) or below (bottom) the input. By default, if there is not enough space within the window the dropdown will appear above the input, otherwise below it.
$3
Type:
BooleanDefault:true
Input types affected:
select-multiple
Usage: Whether the scroll position should reset after adding an item.
$3
Type:
string | RegExp | FunctionDefault:null
Input types affected:
text
Usage: A RegExp or string (will be passed to RegExp constructor internally) or filter function that will need to return
true for a user to successfully add an item.
Example:
`js // Only adds items matching the text test new Choices(element, { addItemFilter: (value) => { return ['orange', 'apple', 'banana'].includes(value); }; });
// only items ending to
-red new Choices(element, { addItemFilter: '-red$'; });`
$3
Type:
BooleanDefault:true
Input types affected:
select-one, select-multiple
Usage: Whether choices and groups should be sorted. If false, choices/groups will appear in the order they were given.
$3
Type:
BooleanDefault:false
Input types affected:
text, select-multiple
Usage: Whether items should be sorted. If false, items will appear in the order they were selected.
$3
Type:
FunctionDefault: sortByAlpha
Input types affected:
select-one, select-multiple
Usage: The function that will sort choices and items before they are displayed (unless a user is searching). By default choices and items are sorted by alphabetical order.
Example:
`js // Sorting via length of label from largest to smallest const example = new Choices(element, { sorter: function(a, b) { return b.label.length - a.label.length; }, }; `
$3
Type:
BooleanDefault:true
Input types affected:
text
Usage: Whether the input should show a placeholder. Used in conjunction with
placeholderValue. If placeholder is set to true and no value is passed to placeholderValue, the passed input's placeholder attribute will be used as the placeholder value.
Note: For select boxes, the recommended way of adding a placeholder is as follows:
`html
`
For backward compatibility,
and are also supported.
$3
Type:
StringDefault:null
Input types affected:
text
Usage: The value of the inputs placeholder.
$3
Type:
StringDefault:null
Input types affected:
select-one
Usage: The value of the search inputs placeholder.
$3
Type:
StringDefault:null
Input types affected:
text, select-one, select-multiple
Usage: Prepend a value to each item added/selected.
$3
Type:
StringDefault:null
Input types affected:
text, select-one, select-multiple
Usage: Append a value to each item added/selected.
$3
Type:
StringDefault:auto
Input types affected:
select-multiple
Usage: Whether selected choices should be removed from the list. By default choices are removed when they are selected in multiple select box. To always render choices pass
always.
$3
Type:
StringDefault:Loading...
Input types affected:
select-one, select-multiple
Usage: The text that is shown whilst choices are being populated via AJAX.
$3
Type:
String/FunctionDefault:No results found
Input types affected:
select-one, select-multiple
Usage: The text that is shown when a user's search has returned no results. Optionally pass a function returning a string.
$3
Type:
String/FunctionDefault:No choices to choose from
Input types affected:
select-multiple, select-one
Usage: The text that is shown when a user has selected all possible choices, or no choices exist. Optionally pass a function returning a string.
$3
Type:
StringDefault:Press to select
Input types affected:
select-multiple, select-one
Usage: The text that is shown when a user hovers over a selectable choice. Set to empty to not reserve space for this text.
$3
Type:
String/FunctionDefault:Press Enter to add "${value}"
Input types affected:
text, select-one, select-multiple
Usage: The text that is shown when a user has inputted a new item but has not pressed the enter key. To access the current input value, pass a function with a
value argument (see the default config for an example), otherwise pass a string.
Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)
$3
Type:
String/FunctionDefault:Remove item"
Input types affected:
text, select-one, select-multiple
Usage: The text/icon for the remove button. To access the item's value, pass a function with a
value argument (see the default config [https://github.com/jshjohnson/Choices#setup] for an example), otherwise pass a string.
Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)
$3
Type:
String/FunctionDefault:Remove item: ${value}"
Input types affected:
text, select-one, select-multiple
Usage: The text for the remove button's aria label. To access the item's value, pass a function with a
value argument (see the default config [https://github.com/jshjohnson/Choices#setup] for an example), otherwise pass a string.
Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)
$3
Type:
String/FunctionDefault:Only ${maxItemCount} values can be added
Input types affected:
text
Usage: The text that is shown when a user has focus on the input but has already reached the max item count. To access the max item count, pass a function with a
maxItemCount argument (see the default config for an example), otherwise pass a string.
$3
Type:
FunctionDefault:strict equality
Input types affected:
select-one, select-multiple
Usage: A custom compare function used when finding choices by value (using
setChoiceByValue).
Example:
`js const example = new Choices(element, { valueComparer: (a, b) => value.trim() === b.trim(), }; `
$3
Type:
StringDefault:
Input types affected:
select-one, select-multiple
Usage: The labelId improves accessibility. If set, it will add aria-labelledby to the choices element.
Usage: Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined here. If you want just extend a little original template then you may use
Choices.defaults.templates to get access to original template function.
Templates receive the full Choices config as the first argument to any template, which allows you to conditionally display things based on the options specified.
@note For each callback,
this refers to the current instance of Choices. This can be useful if you need access to methods (this.disable()).
Usage: Triggered each time a choice is selected by a user, regardless if it changes the value of the input.
choice is a Choice object here (see terminology or typings file)
$3
Payload:
value: string
Input types affected:
text, select-one, select-multiple
Usage: Triggered each time an item is added/removed by a user.
$3
Payload:
value: string, resultCount: number
Input types affected:
select-one, select-multiple
Usage: Triggered when a user types into an input to search choices. When a search is ended, a search event with an empty value with no resultCount is triggered.
$3
Payload: -
Input types affected:
select-one, select-multiple
Usage: Triggered when the dropdown is shown.
$3
Payload: -
Input types affected:
select-one, select-multiple
Usage: Triggered when the dropdown is hidden.
$3
Payload:
el
Input types affected:
select-one, select-multiple
Usage: Triggered when a choice from the dropdown is highlighted. The
el argument is choices.passedElement object that was affected.
Methods
Methods can be called either directly or by chaining:
`js // Calling a method by chaining const choices = new Choices(element, { addItems: false, removeItems: false, }) .setValue(['Set value 1', 'Set value 2']) .disable();
// Calling a method directly const choices = new Choices(element, { addItems: false, removeItems: false, });
choices.setValue(['Set value 1', 'Set value 2']); choices.disable();
`
$3
Input types affected:
text, select-multiple, select-one
Usage: Kills the instance of Choices, removes all event listeners and returns passed input to its initial state.
$3
Input types affected:
text, select-multiple, select-one
Usage: Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM.
Note: This is called implicitly when a new instance of Choices is created. This would be used after a Choices instance had already been destroyed (using
destroy()).
$3
Input types affected:
select-multiple, select-one
Usage: Reads options from backing
element, and recreates choices. Existing items are preserved. When withEvents is truthy, only addItem events are generated.