# Choices.js  A vanilla, lightweight (~18kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency. [Demo](https://joshuajohnson.co.uk/Choices/) --- ### 👉 Please use [develop](https://github.com/jshjohnson/Choices/tree/develop) as the base branch for pull requests. This will be the next major release. Only minor fixes will be pushed into master 👈 --- ## TL;DR * Lightweight * No jQuery dependency * Configurable sorting * Flexible styling * Fast search/filtering * Clean API * Right-to-left support * Custom templates ---- ### Interested in writing your own ES6 JavaScript plugins? Check out [ES6.io](https://ES6.io/friend/JOHNSON) for great tutorials! 💪🏼 ---- ## Installation With [NPM](https://www.npmjs.com/package/choices.js): ```zsh npm install choices.js --save ``` With [Bower](https://bower.io/): ```zsh bower install choices.js --save ``` Or include Choices directly: ```html ``` ## Setup ```js // Pass multiple elements: const choices = new Choices(elements); // Pass single element: 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]); // Passing options (with default options) const choices = new Choices(elements, { silent: false, items: [], choices: [], renderChoiceLimit: -1, maxItemCount: -1, addItems: true, removeItems: true, removeItemButton: false, editItems: false, duplicateItems: true, delimiter: ',', paste: true, searchEnabled: true, searchChoices: true, searchFloor: 1, searchResultLimit: 4, searchFields: ['label', 'value'], position: 'auto', resetScrollPosition: true, regexFilter: null, shouldSort: true, shouldSortItems: false, sortFilter: () => {...}, placeholder: true, placeholderValue: null, searchPlaceholderValue: null, prependValue: null, appendValue: null, renderSelectedChoices: 'auto', loadingText: 'Loading...', noResultsText: 'No results found', noChoicesText: 'No choices to choose from', itemSelectText: 'Press to select', addItemText: (value) => { return `Press Enter to add "${value}"`; }, maxItemText: (maxItemCount) => { return `Only ${maxItemCount} values can be added.`; }, itemComparer: (choice, item) => { return choice === item; }, classNames: { containerOuter: 'choices', containerInner: 'choices__inner', input: 'choices__input', inputCloned: 'choices__input--cloned', list: 'choices__list', listItems: 'choices__list--multiple', listSingle: 'choices__list--single', listDropdown: 'choices__list--dropdown', item: 'choices__item', itemSelectable: 'choices__item--selectable', itemDisabled: 'choices__item--disabled', itemChoice: 'choices__item--choice', placeholder: 'choices__placeholder', group: 'choices__group', groupHeading: 'choices__heading', button: 'choices__button', activeState: 'is-active', focusState: 'is-focused', openState: 'is-open', disabledState: 'is-disabled', highlightedState: 'is-highlighted', hiddenState: 'is-hidden', flippedState: 'is-flipped', loadingState: 'is-loading', noResults: 'has-no-results', noChoices: 'has-no-choices' }, // Choices uses the great Fuse library for searching. You // can find more options here: https://github.com/krisk/Fuse#options fuseOptions: { include: 'score' }, callbackOnInit: null, callbackOnCreateTemplates: null }); ``` ## Terminology | Word | Definition | | ------ | ---------- | | Choice | A choice is a value a user can select. A choice would be equivelant 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 equivelent to a selected option element: `` whereas in the context of a text input an item is equivelant to ``| ## Configuration options ### silent **Type:** `Boolean` **Default:** `false` **Input types affected:** `text`, `select-single`, `select-multiple` **Usage:** Optionally suppress console errors and warnings. ### items **Type:** `Array` **Default:** `[]` **Input types affected:** `text` **Usage:** Add pre-selected items (see terminology) to text input. Pass an array of strings: `['value 1', 'value 2', 'value 3']` Pass an array of objects: ``` [{ value: 'Value 1', label: 'Label 1', id: 1 }, { value: 'Value 2', label: 'Label 2', id: 2, customProperties: { random: 'I am a custom property' } }] ``` ### choices **Type:** `Array` **Default:** `[]` **Input types affected:** `select-one`, `select-multiple` **Usage:** Add choices (see terminology) to select input. Pass an array of objects: ``` [{ value: 'Option 1', label: 'Option 1', selected: true, disabled: false, }, { value: 'Option 2', label: 'Option 2', selected: false, disabled: true, customProperties: { description: 'Custom description about Option 2', random: 'Another random custom property' }, }] ``` ### renderChoiceLimit **Type:** `Number` **Default:** `-1` **Input types affected:** `select-one`, `select-multiple` **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. ### maxItemCount **Type:** `Number` **Default:** `-1` **Input types affected:** `text`, `select-multiple` **Usage:** The amount of items a user can input/select ("-1" indicates no limit). ### addItems **Type:** `Boolean` **Default:** `true` **Input types affected:** `text` **Usage:** Whether a user can add items. ### removeItems **Type:** `Boolean` **Default:** `true` **Input types affected:** `text`, `select-multiple` **Usage:** Whether a user can remove items. ### removeItemButton **Type:** `Boolean` **Default:** `false` **Input types affected:** `text`, `select-one`, `select-multiple` **Usage:** Whether each item should have a remove button. ### editItems **Type:** `Boolean` **Default:** `false` **Input types affected:** `text` **Usage:** Whether a user can edit items. An item's value can be edited by pressing the backspace. ### duplicateItems **Type:** `Boolean` **Default:** `true` **Input types affected:** `text`, `select-multiple` **Usage:** Whether each inputted/chosen item should be unique. ### delimiter **Type:** `String` **Default:** `,` **Input types affected:** `text` **Usage:** What divides each value. The default delimiter seperates each value with a comma: `"Value 1, Value 2, Value 3"`. ### paste **Type:** `Boolean` **Default:** `true` **Input types affected:** `text`, `select-multiple` **Usage:** Whether a user can paste into the input. ### searchEnabled **Type:** `Boolean` **Default:** `true` **Input types affected:** `select-one` **Usage:** Whether a search area should be shown. **Note:** Multiple select boxes will *always* show search areas. ### searchChoices **Type:** `Boolean` **Default:** `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. ### searchFields **Type:** `Array/String` **Default:** `['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']`. ### searchFloor **Type:** `Number` **Default:** `1` **Input types affected:** `select-one`, `select-multiple` **Usage:** The minimum length a search value should be before choices are searched. ### searchResultLimit: 4, **Type:** `Number` **Default:** `4` **Input types affected:** `select-one`, `select-multiple` **Usage:** The maximum amount of search results to show. ### position **Type:** `String` **Default:** `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. ### resetScrollPosition **Type:** `Boolean` **Default:** `true` **Input types affected:** `select-multiple` **Usage:** Whether the scroll position should reset after adding an item. ### regexFilter **Type:** `Regex` **Default:** `null` **Input types affected:** `text` **Usage:** A filter that will need to pass for a user to successfully add an item. ### shouldSort **Type:** `Boolean` **Default:** `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. ### shouldSortItems **Type:** `Boolean` **Default:** `false` **Input types affected:** `text`, `select-multiple` **Usage:** Whether items should be sorted. If false, items will appear in the order they were selected. ### sortFilter **Type:** `Function` **Default:** 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, { sortFilter: function(a, b) { return b.label.length - a.label.length; }, }; ``` ### placeholder **Type:** `Boolean` **Default:** `true` **Input types affected:** `text`, `select-multiple` **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 single select boxes, the recommended way of adding a placeholder is as follows: ```html ``` ### placeholderValue **Type:** `String` **Default:** `null` **Input types affected:** `text`, `select-multiple` **Usage:** The value of the inputs placeholder. ### searchPlaceholderValue **Type:** `String` **Default:** `null` **Input types affected:** `select-one` **Usage:** The value of the search inputs placeholder. ### prependValue **Type:** `String` **Default:** `null` **Input types affected:** `text`, `select-one`, `select-multiple` **Usage:** Prepend a value to each item added/selected. ### appendValue **Type:** `String` **Default:** `null` **Input types affected:** `text`, `select-one`, `select-multiple` **Usage:** Append a value to each item added/selected. ### renderSelectedChoices **Type:** `String` **Default:** `auto` **Input types affected:** `select-one`, `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`. ### loadingText **Type:** `String` **Default:** `Loading...` **Input types affected:** `select-one`, `select-multiple` **Usage:** The text that is shown whilst choices are being populated via AJAX. ### noResultsText **Type:** `String/Function` **Default:** `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. ### noChoicesText **Type:** `String/Function` **Default:** `No choices to choose from` **Input types affected:** `select-multiple` **Usage:** The text that is shown when a user has selected all possible choices. Optionally pass a function returning a string. ### itemSelectText **Type:** `String` **Default:** `Press to select` **Input types affected:** `select-multiple`, `select-one` **Usage:** The text that is shown when a user hovers over a selectable choice. ### addItemText **Type:** `String/Function` **Default:** `Press Enter to add "${value}"` **Input types affected:** `text` **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](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string. ### maxItemText **Type:** `String/Function` **Default:** `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](https://github.com/jshjohnson/Choices#maxitemcount). To access the max item count, pass a function with a `maxItemCount` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string. ### itemComparer **Type:** `Function` **Default:** `strict equality` **Input types affected:** `select-one`, `select-multiple` **Usage:** Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a `itemComparer` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example). ### classNames **Type:** `Object` **Default:** ``` classNames: { containerOuter: 'choices', containerInner: 'choices__inner', input: 'choices__input', inputCloned: 'choices__input--cloned', list: 'choices__list', listItems: 'choices__list--multiple', listSingle: 'choices__list--single', listDropdown: 'choices__list--dropdown', item: 'choices__item', itemSelectable: 'choices__item--selectable', itemDisabled: 'choices__item--disabled', itemOption: 'choices__item--choice', group: 'choices__group', groupHeading : 'choices__heading', button: 'choices__button', activeState: 'is-active', focusState: 'is-focused', openState: 'is-open', disabledState: 'is-disabled', highlightedState: 'is-highlighted', hiddenState: 'is-hidden', flippedState: 'is-flipped', selectedState: 'is-highlighted', } ``` **Input types affected:** `text`, `select-one`, `select-multiple` **Usage:** Classes added to HTML generated by Choices. By default classnames follow the [BEM](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/) notation. ## Callbacks **Note:** For each callback, `this` refers to the current instance of Choices. This can be useful if you need access to methods (`this.disable()`) or the config object (`this.config`). ### callbackOnInit **Type:** `Function` **Default:** `null` **Input types affected:** `text`, `select-one`, `select-multiple` **Usage:** Function to run once Choices initialises. ### callbackOnCreateTemplates **Type:** `Function` **Default:** `null` **Arguments:** `template` **Input types affected:** `text`, `select-one`, `select-multiple` **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](https://github.com/jshjohnson/Choices/blob/67f29c286aa21d88847adfcd6304dc7d068dc01f/assets/scripts/src/choices.js#L1993-L2067). **Example:** ```js const example = new Choices(element, { callbackOnCreateTemplates: function (template) { var classNames = this.config.classNames; return { item: (data) => { return template(`