Choices/README.md

968 lines
30 KiB
Markdown
Raw Normal View History

2018-10-28 12:17:08 +01:00
# Choices.js ![Build Status](https://travis-ci.org/jshjohnson/Choices.svg?branch=master) [![](https://data.jsdelivr.com/v1/package/npm/choices.js/badge?style=rounded)](https://www.jsdelivr.com/package/npm/choices.js) [![npm](https://img.shields.io/npm/v/choices.js.svg)](https://www.npmjs.com/package/choices.js) [![codebeat badge](https://codebeat.co/badges/55120150-5866-42d8-8010-6aaaff5d3fa1)](https://codebeat.co/projects/github-com-jshjohnson-choices-master)
A vanilla, lightweight (~22kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.
2016-08-09 14:59:30 +02:00
2016-07-25 10:08:14 +02:00
[Demo](https://joshuajohnson.co.uk/Choices/)
## TL;DR
2016-09-04 21:40:37 +02:00
* Lightweight
* No jQuery dependency
* Configurable sorting
* Flexible styling
* Fast search/filtering
* Clean API
2016-09-04 23:23:20 +02:00
* Right-to-left support
2016-09-30 22:29:18 +02:00
* Custom templates
2016-09-04 21:40:08 +02:00
2017-01-24 13:22:19 +01:00
----
### Interested in writing your own ES6 JavaScript plugins? Check out [ES6.io](https://ES6.io/friend/JOHNSON) for great tutorials! 💪🏼
2017-01-24 13:22:19 +01:00
----
2016-10-18 15:15:00 +02:00
## Installation
2016-10-20 23:00:25 +02:00
With [NPM](https://www.npmjs.com/package/choices.js):
2016-11-08 10:51:56 +01:00
```zsh
2018-07-19 16:32:44 +02:00
npm install choices.js
2016-10-20 23:00:25 +02:00
```
2017-01-01 16:32:09 +01:00
2018-07-19 16:32:25 +02:00
With [Yarn](https://yarnpkg.com/):
2016-11-08 10:51:56 +01:00
```zsh
2018-07-19 16:32:25 +02:00
yarn add choices.js
2016-10-20 23:00:25 +02:00
```
2017-01-01 16:32:09 +01:00
2018-10-27 18:01:54 +02:00
From a [CDN](https://www.jsdelivr.com/package/npm/choices.js):
2019-05-28 19:52:26 +02:00
**Note:** There is sometimes a delay before the latest version of Choices is reflected on the CDN.
2018-10-28 12:13:43 +01:00
2018-10-27 18:01:54 +02:00
```html
<!-- Include base CSS (optional) -->
2019-03-11 13:19:52 +01:00
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/base.min.css">
2018-10-27 18:01:54 +02:00
<!-- Include Choices CSS -->
2019-03-11 13:19:52 +01:00
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css">
2018-10-27 18:01:54 +02:00
<!-- Include Choices JavaScript -->
2019-03-11 13:19:52 +01:00
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
2018-10-27 18:01:54 +02:00
```
2018-10-27 18:00:40 +02:00
2016-10-20 23:00:25 +02:00
Or include Choices directly:
2017-01-01 16:32:09 +01:00
2016-06-02 10:12:55 +02:00
```html
2016-07-11 11:25:38 +02:00
<!-- Include base CSS (optional) -->
2018-10-09 13:26:47 +02:00
<link rel="stylesheet" href="public/assets/styles/base.min.css">
2016-07-11 11:25:38 +02:00
<!-- Include Choices CSS -->
2018-10-09 13:26:47 +02:00
<link rel="stylesheet" href="public/assets/styles/choices.min.css">
2016-07-11 11:25:38 +02:00
<!-- Include Choices JavaScript -->
2018-10-09 13:26:47 +02:00
<script src="/public/assets/scripts/choices.min.js"></script>
2016-10-20 23:00:25 +02:00
```
## Setup
If you pass a selector which targets multiple elements, an array of Choices instances
will be returned. If you target one element, that instance will be returned.
2016-10-20 23:00:25 +02:00
```js
// Pass multiple elements:
const [firstInstance, secondInstance] = new Choices(elements);
2016-10-20 23:00:25 +02:00
// Pass single element:
const choices = new Choices(element);
2016-10-20 23:00:25 +02:00
// Pass reference
const choices = new Choices('[data-trigger]');
2016-10-20 23:00:25 +02:00
const choices = new Choices('.js-choice');
2016-08-01 21:00:24 +02:00
2016-10-20 23:00:25 +02:00
// Pass jQuery element
const choices = new Choices($('.js-choice')[0]);
2016-10-20 23:00:25 +02:00
// Passing options (with default options)
const choices = new Choices(elements, {
2017-05-18 18:56:29 +02:00
silent: false,
2016-10-20 23:00:25 +02:00
items: [],
choices: [],
2017-07-31 17:22:21 +02:00
renderChoiceLimit: -1,
2016-10-20 23:00:25 +02:00
maxItemCount: -1,
addItems: true,
addItemFilterFn: null,
2016-10-20 23:00:25 +02:00
removeItems: true,
removeItemButton: false,
editItems: false,
duplicateItemsAllowed: true,
2016-10-20 23:00:25 +02:00
delimiter: ',',
paste: true,
2017-05-18 18:56:29 +02:00
searchEnabled: true,
searchChoices: true,
2016-10-20 23:00:25 +02:00
searchFloor: 1,
2017-06-27 17:35:46 +02:00
searchResultLimit: 4,
searchFields: ['label', 'value'],
2017-02-21 21:47:12 +01:00
position: 'auto',
2017-01-12 15:13:21 +01:00
resetScrollPosition: true,
2016-10-20 23:00:25 +02:00
shouldSort: true,
shouldSortItems: false,
2017-12-19 13:19:43 +01:00
sortFn: () => {...},
2016-10-20 23:00:25 +02:00
placeholder: true,
placeholderValue: null,
2017-08-03 13:48:32 +02:00
searchPlaceholderValue: null,
2016-10-20 23:00:25 +02:00
prependValue: null,
appendValue: null,
renderSelectedChoices: 'auto',
2016-10-20 23:00:25 +02:00
loadingText: 'Loading...',
noResultsText: 'No results found',
2016-10-20 23:00:25 +02:00
noChoicesText: 'No choices to choose from',
itemSelectText: 'Press to select',
2016-11-07 15:05:31 +01:00
addItemText: (value) => {
return `Press Enter to add <b>"${value}"</b>`;
},
maxItemText: (maxItemCount) => {
2018-10-28 12:18:35 +01:00
return `Only ${maxItemCount} values can be added`;
2016-11-07 15:05:31 +01:00
},
itemComparer: (choice, item) => {
return choice === item;
},
2016-10-20 23:00:25 +02:00
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',
2017-08-03 14:15:49 +02:00
placeholder: 'choices__placeholder',
group: 'choices__group',
2017-08-03 14:15:49 +02:00
groupHeading: 'choices__heading',
button: 'choices__button',
activeState: 'is-active',
focusState: 'is-focused',
openState: 'is-open',
2018-10-27 18:00:40 +02:00
disabledState: 'is-disabled',
highlightedState: 'is-highlighted',
hiddenState: 'is-hidden',
flippedState: 'is-flipped',
loadingState: 'is-loading',
2017-08-03 14:15:49 +02:00
noResults: 'has-no-results',
noChoices: 'has-no-choices'
2016-10-20 23:00:25 +02:00
},
2017-01-01 17:00:31 +01:00
// Choices uses the great Fuse library for searching. You
// can find more options here: https://github.com/krisk/Fuse#options
fuseOptions: {
2017-08-03 14:15:49 +02:00
include: 'score'
2017-01-01 17:00:31 +01:00
},
2016-10-20 23:00:25 +02:00
callbackOnInit: null,
2017-08-03 14:15:49 +02:00
callbackOnCreateTemplates: null
2016-10-20 23:00:25 +02:00
});
2016-06-02 10:12:55 +02:00
```
## Terminology
| Word | Definition |
| ------ | ---------- |
2019-06-30 21:02:52 +02:00
| Choice | A choice is a value a user can select. A choice would be equivalent to the `<option></option>` element within a select input. |
| Group | A group is a collection of choices. A group should be seen as equivalent to a `<optgroup></optgroup>` element within a select input.|
2019-06-30 21:02:52 +02:00
| 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: `<option value="Hello" selected></option>` whereas in the context of a text input an item is equivalent to `<input type="text" value="Hello">`|
2016-06-02 10:12:55 +02:00
2016-08-05 08:42:35 +02:00
2016-07-03 11:54:20 +02:00
## Configuration options
2017-05-18 18:56:29 +02:00
### silent
**Type:** `Boolean` **Default:** `false`
**Input types affected:** `text`, `select-single`, `select-multiple`
2017-05-18 19:04:49 +02:00
**Usage:** Optionally suppress console errors and warnings.
2017-05-18 18:56:29 +02:00
### items
2016-08-20 13:39:37 +02:00
**Type:** `Array` **Default:** `[]`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-06-22 00:06:23 +02:00
**Usage:** Add pre-selected items (see terminology) to text input.
2016-08-06 12:15:56 +02:00
Pass an array of strings:
2016-06-22 00:06:23 +02:00
`['value 1', 'value 2', 'value 3']`
Pass an array of objects:
```
[{
2017-05-18 19:04:49 +02:00
value: 'Value 1',
2017-05-18 19:08:55 +02:00
label: 'Label 1',
id: 1
2016-06-22 00:06:23 +02:00
},
{
2017-05-18 19:08:55 +02:00
value: 'Value 2',
label: 'Label 2',
id: 2,
customProperties: {
2017-06-29 09:53:04 +02:00
random: 'I am a custom property'
}
2016-06-22 00:06:23 +02:00
}]
```
2016-06-02 10:12:55 +02:00
### choices
2016-08-20 13:39:37 +02:00
**Type:** `Array` **Default:** `[]`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
**Usage:** Add choices (see terminology) to select input.
2016-08-06 12:15:56 +02:00
2016-07-30 16:12:22 +02:00
Pass an array of objects:
```
2016-08-20 12:38:57 +02:00
[{
2017-05-18 19:08:55 +02:00
value: 'Option 1',
label: 'Option 1',
selected: true,
disabled: false,
2016-07-30 16:12:22 +02:00
},
2016-08-20 12:38:57 +02:00
{
2017-05-18 19:08:55 +02:00
value: 'Option 2',
label: 'Option 2',
selected: false,
disabled: true,
customProperties: {
description: 'Custom description about Option 2',
random: 'Another random custom property'
},
2016-07-30 16:12:22 +02:00
}]
```
2017-07-31 17:22:21 +02:00
### 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
2016-08-20 13:39:37 +02:00
**Type:** `Number` **Default:** `-1`
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** The amount of items a user can input/select ("-1" indicates no limit).
### addItems
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-07-30 16:12:22 +02:00
2016-09-30 22:28:43 +02:00
**Usage:** Whether a user can add items.
2016-06-02 10:12:55 +02:00
### removeItems
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Whether a user can remove items.
2016-06-02 10:12:55 +02:00
2016-08-20 12:38:57 +02:00
### removeItemButton
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `false`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-09-30 22:28:43 +02:00
**Usage:** Whether each item should have a remove button.
2016-06-02 10:12:55 +02:00
### editItems
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `false`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-07-30 16:12:22 +02:00
2016-09-30 22:30:38 +02:00
**Usage:** Whether a user can edit items. An item's value can be edited by pressing the backspace.
2016-06-02 10:12:55 +02:00
### duplicateItemsAllowed
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
**Usage:** Whether duplicate inputted/chosen items are allowed
2016-06-02 10:12:55 +02:00
### delimiter
2016-08-20 13:39:37 +02:00
**Type:** `String` **Default:** `,`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-07-30 16:12:22 +02:00
2016-09-30 22:28:43 +02:00
**Usage:** What divides each value. The default delimiter seperates each value with a comma: `"Value 1, Value 2, Value 3"`.
2016-06-02 10:12:55 +02:00
### paste
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Whether a user can paste into the input.
2016-06-02 10:12:55 +02:00
2017-05-18 18:56:29 +02:00
### searchEnabled
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`
2016-08-02 22:38:00 +02:00
2017-05-18 18:56:29 +02:00
**Usage:** Whether a search area should be shown. **Note:** Multiple select boxes will *always* show search areas.
2016-08-02 22:38:00 +02:00
### searchChoices
**Type:** `Boolean` **Default:** `true`
**Input types affected:** `select-one`
2017-05-18 18:56:29 +02:00
**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.
2017-06-27 17:35:46 +02:00
### searchResultLimit: 4,
2017-06-27 17:30:08 +02:00
**Type:** `Number` **Default:** `4`
**Input types affected:** `select-one`, `select-multiple`
**Usage:** The maximum amount of search results to show.
2017-02-21 21:47:12 +01:00
### position
2017-02-21 21:50:46 +01:00
**Type:** `String` **Default:** `auto`
2016-08-02 22:38:00 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
**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.
2016-06-02 10:12:55 +02:00
2017-01-14 15:51:38 +01:00
### resetScrollPosition
**Type:** `Boolean` **Default:** `true`
**Input types affected:** `select-multiple`
**Usage:** Whether the scroll position should reset after adding an item.
### addItemFilterFn
**Type:** `Function` **Default:** `null`
**Input types affected:** `text`
**Usage:** A 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, {
addItemFilterFn: (value) => {
return (value !== 'test');
};
});
```
### shouldSort
**Type:** `Boolean` **Default:** `true`
**Input types affected:** `select-one`, `select-multiple`
2017-07-12 10:05:36 +02:00
**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.
2017-12-19 13:19:43 +01:00
### sortFn
2016-08-20 13:39:37 +02:00
**Type:** `Function` **Default:** sortByAlpha
2016-08-20 13:39:37 +02:00
**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.
2016-08-20 13:39:37 +02:00
**Example:**
```js
// Sorting via length of label from largest to smallest
const example = new Choices(element, {
2017-12-19 13:19:43 +01:00
sortFn: function(a, b) {
return b.label.length - a.label.length;
},
};
```
### placeholder
2016-08-20 13:39:37 +02:00
**Type:** `Boolean` **Default:** `true`
2016-06-02 10:12:55 +02:00
2017-08-03 10:55:31 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**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.
2016-06-02 10:12:55 +02:00
2017-08-03 13:27:33 +02:00
**Note:** For single select boxes, the recommended way of adding a placeholder is as follows:
```html
<select>
<option placeholder>This is a placeholder</option>
<option>...</option>
<option>...</option>
<option>...</option>
</select>
```
### placeholderValue
2016-08-20 13:39:37 +02:00
**Type:** `String` **Default:** `null`
2016-06-02 10:12:55 +02:00
2017-08-03 12:13:23 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** The value of the inputs placeholder.
2016-06-02 10:12:55 +02:00
### searchPlaceholderValue
2017-08-03 10:55:31 +02:00
**Type:** `String` **Default:** `null`
**Input types affected:** `select-one`
**Usage:** The value of the search inputs placeholder.
### prependValue
2016-08-20 13:39:37 +02:00
**Type:** `String` **Default:** `null`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Prepend a value to each item added/selected.
2016-06-02 10:12:55 +02:00
### appendValue
2016-08-20 13:39:37 +02:00
**Type:** `String` **Default:** `null`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Append a value to each item added/selected.
2016-06-02 10:12:55 +02:00
### renderSelectedChoices
**Type:** `String` **Default:** `auto`
2017-09-19 15:22:00 +02:00
**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`.
### loadingText
2016-08-20 13:39:37 +02:00
**Type:** `String` **Default:** `Loading...`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** The text that is shown whilst choices are being populated via AJAX.
### noResultsText
**Type:** `String/Function` **Default:** `No results found`
2016-08-20 13:39:37 +02:00
**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`
2016-08-20 13:39:37 +02:00
**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.
2016-06-02 10:12:55 +02:00
2016-09-26 15:07:09 +02:00
### 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.
2016-11-07 15:05:31 +01:00
### 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
2018-10-28 12:18:35 +01:00
**Type:** `String/Function` **Default:** `Only ${maxItemCount} values can be added`
2016-11-07 15:05:31 +01:00
**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
2016-08-20 13:39:37 +02:00
**Type:** `Object` **Default:**
2016-06-22 00:06:23 +02:00
```
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',
2016-06-22 00:06:23 +02:00
}
```
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**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.
2016-06-02 10:12:55 +02:00
2016-11-07 14:53:56 +01:00
## 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`
2016-06-02 10:12:55 +02:00
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Function to run once Choices initialises.
2016-06-02 10:12:55 +02:00
2016-09-30 14:50:23 +02:00
### callbackOnCreateTemplates
2016-11-07 14:53:56 +01:00
**Type:** `Function` **Default:** `null` **Arguments:** `template`
2016-09-30 14:50:23 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2018-11-03 13:42:42 +01:00
**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/master/src/scripts/templates.js).
2016-09-30 14:50:23 +02:00
**Example:**
```js
const example = new Choices(element, {
2016-11-07 14:53:56 +01:00
callbackOnCreateTemplates: function (template) {
2016-09-30 14:50:23 +02:00
return {
2018-11-03 13:42:42 +01:00
item: (classNames, data) => {
2016-09-30 14:50:23 +02:00
return template(`
<div class="${classNames.item} ${data.highlighted ? classNames.highlightedState : classNames.itemSelectable} ${data.placeholder ? classNames.placeholder : ''}" data-item data-id="${data.id}" data-value="${data.value}" ${data.active ? 'aria-selected="true"' : ''} ${data.disabled ? 'aria-disabled="true"' : ''}>
2016-09-30 14:50:23 +02:00
<span>&bigstar;</span> ${data.label}
</div>
`);
2016-09-30 14:50:23 +02:00
},
2018-11-03 13:42:42 +01:00
choice: (classNames, data) => {
2016-09-30 14:50:23 +02:00
return template(`
2016-11-07 14:53:56 +01:00
<div class="${classNames.item} ${classNames.itemChoice} ${data.disabled ? classNames.itemDisabled : classNames.itemSelectable}" data-select-text="${this.config.itemSelectText}" data-choice ${data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable'} data-id="${data.id}" data-value="${data.value}" ${data.groupId > 0 ? 'role="treeitem"' : 'role="option"'}>
<span>&bigstar;</span> ${data.label}
</div>
`);
2016-09-30 14:50:23 +02:00
},
};
}
});
```
2017-01-01 16:32:09 +01:00
## Events
**Note:** Events fired by Choices behave the same as standard events. Each event is triggered on the element passed to Choices (accessible via `this.passedElement`. Arguments are accessible within the `event.detail` object.
2017-01-01 16:32:09 +01:00
**Example:**
```js
const element = document.getElementById('example');
const example = new Choices(element);
element.addEventListener('addItem', function(event) {
// do something creative here...
console.log(event.detail.id);
console.log(event.detail.value);
2017-03-01 20:07:22 +01:00
console.log(event.detail.label);
2018-03-08 10:35:01 +01:00
console.log(event.detail.customProperties);
2017-01-01 16:32:09 +01:00
console.log(event.detail.groupValue);
}, false);
// or
2017-01-01 16:32:09 +01:00
const example = new Choices(document.getElementById('example'));
example.passedElement.element.addEventListener('addItem', function(event) {
2017-01-01 16:32:09 +01:00
// do something creative here...
console.log(event.detail.id);
console.log(event.detail.value);
2017-03-01 20:07:22 +01:00
console.log(event.detail.label);
2018-03-08 10:35:01 +01:00
console.log(event.detail.customProperties);
2017-01-01 16:32:09 +01:00
console.log(event.detail.groupValue);
}, false);
```
### addItem
2017-07-19 21:29:44 +02:00
**Arguments:** `id, value, label, groupValue, keyCode`
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2017-01-01 16:32:09 +01:00
**Usage:** Triggered each time an item is added (programmatically or by the user).
2016-06-02 10:12:55 +02:00
2017-01-01 16:32:09 +01:00
### removeItem
2017-03-01 20:07:22 +01:00
**Arguments:** `id, value, label, groupValue`
2016-09-29 14:16:50 +02:00
2017-01-01 16:32:09 +01:00
**Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Triggered each time an item is removed (programmatically or by the user).
### highlightItem
2017-03-01 20:07:22 +01:00
**Arguments:** `id, value, label, groupValue`
2017-01-01 16:32:09 +01:00
**Input types affected:** `text`, `select-multiple`
**Usage:** Triggered each time an item is highlighted.
### unhighlightItem
2017-03-01 20:07:22 +01:00
**Arguments:** `id, value, label, groupValue`
2017-01-01 16:32:09 +01:00
**Input types affected:** `text`, `select-multiple`
**Usage:** Triggered each time an item is unhighlighted.
2017-03-28 15:41:12 +02:00
### choice
2017-07-19 21:29:44 +02:00
**Arguments:** `value, keyCode`
2017-03-28 15:41:12 +02:00
**Input types affected:** `select-one`, `select-multiple`
2017-03-28 15:48:37 +02:00
**Usage:** Triggered each time a choice is selected **by a user**, regardless if it changes the value of the input.
2017-03-28 15:41:12 +02:00
2017-01-01 16:32:09 +01:00
### change
**Arguments:** `value`
**Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Triggered each time an item is added/removed **by a user**.
### search
2017-07-31 17:17:03 +02:00
**Arguments:** `value`, `resultCount`
2017-07-31 17:06:26 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-09-29 14:16:50 +02:00
2017-01-01 16:32:09 +01:00
**Usage:** Triggered when a user types into an input to search choices.
2016-06-02 10:12:55 +02:00
### showDropdown
2017-07-31 17:17:03 +02:00
**Arguments:** -
2017-07-31 17:06:26 +02:00
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Triggered when the dropdown is shown.
### hideDropdown
2017-07-31 17:06:26 +02:00
**Arguments:** -
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Triggered when the dropdown is hidden.
2018-07-02 21:13:10 +02:00
### highlightChoice
**Arguments:** `el`
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Triggered when a choice from the dropdown is highlighted. The `el` argument is the HTML element node object that was affected.
2016-06-02 10:12:55 +02:00
## 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
2016-07-01 10:56:33 +02:00
const choices = new Choices(element, {
addItems: false,
removeItems: false,
2016-07-01 10:56:33 +02:00
});
choices.setValue(['Set value 1', 'Set value 2'])
choices.disable();
```
2016-08-05 08:42:35 +02:00
### destroy();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`, `select-one`
2016-08-05 08:42:35 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Kills the instance of Choices, removes all event listeners and returns passed input to its initial state.
2016-08-05 08:42:35 +02:00
### init();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`, `select-one`
2016-08-05 08:42:35 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM.
2016-08-05 08:42:35 +02:00
**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()`).
2016-08-05 08:42:35 +02:00
### highlightAll();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Highlight each chosen item (selected items can be removed).
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### unhighlightAll();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Un-highlight each chosen item.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
2017-11-21 15:10:29 +01:00
### removeActiveItemsByValue(value);
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Remove each item by a given value.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### removeActiveItems(excludedId);
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Remove each selectable item.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### removeHighlightedItems();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Remove each item the user has selected.
2016-06-22 00:06:23 +02:00
### showDropdown();
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Show option list dropdown (only affects select inputs).
2016-06-22 00:12:10 +02:00
### hideDropdown();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Hide option list dropdown (only affects select inputs).
2016-06-22 00:06:23 +02:00
### setChoices(choices, value, label, replaceChoices);
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Set choices of select input via an array of objects, a value name and a label name. This behaves the same as passing items via the `choices` option but can be called after initialising Choices. This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices. Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc). Passing an empty array as the first parameter, and a true `replaceChoices` is the same as calling `clearChoices` (see below).
2016-08-20 13:39:37 +02:00
**Example 1:**
```js
2016-08-02 22:10:53 +02:00
const example = new Choices(element);
2016-08-02 22:10:53 +02:00
example.setChoices([
{value: 'One', label: 'Label One', disabled: true},
{value: 'Two', label: 'Label Two', selected: true},
{value: 'Three', label: 'Label Three'},
], 'value', 'label', false);
```
2016-06-22 00:12:10 +02:00
2016-08-20 13:39:37 +02:00
**Example 2:**
2016-08-02 22:10:53 +02:00
```js
const example = new Choices(element);
example.setChoices([{
label: 'Group one',
id: 1,
disabled: false,
choices: [
{value: 'Child One', label: 'Child One', selected: true},
{value: 'Child Two', label: 'Child Two', disabled: true},
{value: 'Child Three', label: 'Child Three'},
]
},
2016-08-02 22:10:53 +02:00
{
label: 'Group two',
id: 2,
disabled: false,
choices: [
{value: 'Child Four', label: 'Child Four', disabled: true},
{value: 'Child Five', label: 'Child Five'},
{value: 'Child Six', label: 'Child Six', customProperties: {
description: 'Custom description about child six',
random: 'Another random custom property'
}},
]
2016-10-19 08:36:41 +02:00
}], 'value', 'label', false);
2016-08-02 22:10:53 +02:00
```
### clearChoices();
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Clear all choices from select
### getValue(valueOnly)
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-08-20 13:39:37 +02:00
**Usage:** Get value(s) of input (i.e. inputted items (text) or selected choices (select)). Optionally pass an argument of `true` to only return values rather than value objects.
2016-08-20 13:39:37 +02:00
**Example:**
```js
const example = new Choices(element);
const values = example.getValue(true); // returns ['value 1', 'value 2'];
const valueArray = example.getValue(); // returns [{ active: true, choiceId: 1, highlighted: false, id: 1, label: 'Label 1', value: 'Value 1'}, { active: true, choiceId: 2, highlighted: false, id: 2, label: 'Label 2', value: 'Value 2'}];
```
### setValue(args);
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Set value of input based on an array of objects or strings. This behaves exactly the same as passing items via the `items` option but can be called after initialising Choices.
2016-08-20 13:39:37 +02:00
**Example:**
```js
const example = new Choices(element);
// via an array of objects
example.setValue([
{value: 'One', label: 'Label One'},
{value: 'Two', label: 'Label Two'},
{value: 'Three', label: 'Label Three'},
]);
2016-06-22 00:06:23 +02:00
// or via an array of strings
example.setValue(['Four','Five','Six']);
```
2017-11-11 14:40:18 +01:00
### setChoiceByValue(value);
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Set value of input based on existing Choice. `value` can be either a single string or an array of strings
2016-08-20 13:39:37 +02:00
**Example:**
```js
const example = new Choices(element, {
choices: [
{value: 'One', label: 'Label One'},
{value: 'Two', label: 'Label Two', disabled: true},
{value: 'Three', label: 'Label Three'},
],
});
2017-11-11 14:40:18 +01:00
example.setChoiceByValue('Two'); // Choice with value of 'Two' has now been selected.
```
2016-06-22 00:12:10 +02:00
2016-08-03 22:51:24 +02:00
### clearStore();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Removes all items, choices and groups. Use with caution.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### clearInput();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`
2016-07-30 16:12:22 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Clear input of any user inputted text.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### disable();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2017-06-30 15:37:11 +02:00
**Usage:** Disables input from accepting new value/selecting further choices.
2016-08-02 22:14:13 +02:00
### enable();
2016-08-20 13:39:37 +02:00
**Input types affected:** `text`, `select-one`, `select-multiple`
2016-08-02 22:14:13 +02:00
2016-08-20 13:39:37 +02:00
**Usage:** Enables input to accept new values/select further choices.
2016-06-22 00:06:23 +02:00
2016-06-22 00:12:10 +02:00
### ajax(fn);
2016-08-20 13:39:37 +02:00
**Input types affected:** `select-one`, `select-multiple`
2016-07-30 16:12:22 +02:00
2016-10-12 14:54:14 +02:00
**Usage:** Populate choices/groups via a callback.
2016-06-22 00:06:23 +02:00
2016-08-20 13:39:37 +02:00
**Example:**
2016-08-02 22:14:13 +02:00
```js
var example = new Choices(element);
example.ajax(function(callback) {
fetch(url)
.then(function(response) {
response.json().then(function(data) {
callback(data, 'value', 'label');
});
})
.catch(function(error) {
console.log(error);
});
2016-08-02 22:14:13 +02:00
});
```
2018-03-19 11:46:28 +01:00
**Example 2:**
2018-03-19 11:48:29 +01:00
If your structure differs from `data.value` and `data.key` structure you can write your own `key` and `value` into the `callback` function. This could be useful when you don't want to transform the given response.
2018-03-19 11:46:28 +01:00
```js
const example = new Choices(element)
example.ajax(function(callback) {
fetch(url)
.then(function(response) {
response.json().then(function(data) {
callback(data, 'data.key', 'data.value');
});
})
.catch(function(error) {
console.log(error);
});
});
```
2016-06-02 10:12:55 +02:00
## Browser compatibility
2016-08-20 13:39:37 +02:00
Choices is compiled using [Babel](https://babeljs.io/) to enable support for [ES5 browsers](http://caniuse.com/#feat=es5). If you need to support a browser that does not support one of the features listed below, I suggest including a polyfill from the very good [polyfill.io](https://cdn.polyfill.io/v2/docs/):
**Polyfill example used for the demo:**
```html
<script src="https://cdn.polyfill.io/v2/polyfill.js?features=es5,fetch,Element.prototype.classList,requestAnimationFrame,Node.insertBefore,Node.firstChild,CustomEvent"></script>
2016-08-20 13:39:37 +02:00
```
**Features used in Choices:**
* Array.prototype.forEach
* Array.prototype.map
* Array.prototype.find
* Array.prototype.some
* Array.prototype.includes
* Array.from
2016-08-20 13:39:37 +02:00
* Array.prototype.reduce
* Array.prototype.indexOf
2017-07-24 14:49:35 +02:00
* Object.assign
2016-08-20 13:39:37 +02:00
* Element.prototype.classList
* window.requestAnimationFrame
* CustomEvent
2016-06-02 10:12:55 +02:00
## Development
To setup a local environment: clone this repo, navigate into it's directory in a terminal window and run the following command:
2016-06-22 00:06:23 +02:00
```npm install```
2016-06-02 10:12:55 +02:00
### NPM tasks
| Task | Usage |
| -------------------- | ------------------------------------------------------------ |
| `npm run start` | Fire up local server for development |
2018-10-11 20:46:50 +02:00
| `npm run test:unit` | Run sequence of tests once |
| `npm run test:unit:watch` | Fire up test server and re-test on file change |
2018-10-27 19:12:15 +02:00
| `npm run test:e2e` | Run sequence of e2e tests (with local server) |
| `npm run test` | Run both unit and e2e tests |
| `npm run cypress:open` | Run Cypress e2e tests (GUI) |
| `npm run cypress:run` | Run Cypress e2e tests (CLI) |
| `npm run js:build` | Compile Choices to an uglified JavaScript file |
| `npm run css:watch` | Watch SCSS files for changes. On a change, run build process |
| `npm run css:build` | Compile, minify and prefix SCSS files to CSS |
2016-06-02 10:12:55 +02:00
## License
MIT License
2016-08-04 18:32:08 +02:00
## Web component
Want to use Choices as a web component? You're in luck. Adidas have built one for their design system which can be found [here](https://github.com/adidas/choicesjs-stencil).
2016-08-04 18:32:08 +02:00
## Misc
2016-08-04 18:33:25 +02:00
Thanks to [@mikefrancis](https://github.com/mikefrancis/) for [sending me on a hunt](https://twitter.com/_mikefrancis/status/701797835826667520) for a non-jQuery solution for select boxes that eventually led to this being built!