Choices.js

A vanilla JS customisable select box/text input plugin

README

Choices.js Actions Status Actions Status npm


A vanilla, lightweight (~19kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.


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 for great tutorials! 💪🏼


Sponsored by:

Wanderer Maps logo



Table of Contents



Installation


With NPM:

  1. ```zsh
  2. npm install choices.js
  3. ```

With Yarn:

  1. ```zsh
  2. yarn add choices.js
  3. ```

From a CDN:

Note: There is sometimes a delay before the latest version of Choices is reflected on the CDN.

  1. ``` html
  2. <link
  3.   rel="stylesheet"
  4.   href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/base.min.css"
  5. />
  6. <link
  7.   rel="stylesheet"
  8.   href="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/styles/base.min.css"
  9. />
  10. <link
  11.   rel="stylesheet"
  12.   href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"
  13. />
  14. <link
  15.   rel="stylesheet"
  16.   href="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/styles/choices.min.css"
  17. />
  18. <script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
  19. <script src="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/scripts/choices.min.js"></script>
  20. ```

Or include Choices directly:

  1. ``` html
  2. <link rel="stylesheet" href="public/assets/styles/base.min.css" />
  3. <link rel="stylesheet" href="public/assets/styles/choices.min.css" />
  4. <script src="/public/assets/scripts/choices.min.js"></script>
  5. ```

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.

  1. ``` js
  2.   // Pass single element
  3.   const element = document.querySelector('.js-choice');
  4.   const choices = new Choices(element);

  5.   // Pass reference
  6.   const choices = new Choices('[data-trigger]');
  7.   const choices = new Choices('.js-choice');

  8.   // Pass jQuery element
  9.   const choices = new Choices($('.js-choice')[0]);

  10.   // Passing options (with default options)
  11.   const choices = new Choices(element, {
  12.     silent: false,
  13.     items: [],
  14.     choices: [],
  15.     renderChoiceLimit: -1,
  16.     maxItemCount: -1,
  17.     addItems: true,
  18.     addItemFilter: null,
  19.     removeItems: true,
  20.     removeItemButton: false,
  21.     editItems: false,
  22.     allowHTML: true,
  23.     duplicateItemsAllowed: true,
  24.     delimiter: ',',
  25.     paste: true,
  26.     searchEnabled: true,
  27.     searchChoices: true,
  28.     searchFloor: 1,
  29.     searchResultLimit: 4,
  30.     searchFields: ['label', 'value'],
  31.     position: 'auto',
  32.     resetScrollPosition: true,
  33.     shouldSort: true,
  34.     shouldSortItems: false,
  35.     sorter: () => {...},
  36.     placeholder: true,
  37.     placeholderValue: null,
  38.     searchPlaceholderValue: null,
  39.     prependValue: null,
  40.     appendValue: null,
  41.     renderSelectedChoices: 'auto',
  42.     loadingText: 'Loading...',
  43.     noResultsText: 'No results found',
  44.     noChoicesText: 'No choices to choose from',
  45.     itemSelectText: 'Press to select',
  46.     uniqueItemText: 'Only unique values can be added',
  47.     customAddItemText: 'Only values matching specific conditions can be added',
  48.     addItemText: (value) => {
  49.       return `Press Enter to add <b>"${value}"</b>`;
  50.     },
  51.     maxItemText: (maxItemCount) => {
  52.       return `Only ${maxItemCount} values can be added`;
  53.     },
  54.     valueComparer: (value1, value2) => {
  55.       return value1 === value2;
  56.     },
  57.     classNames: {
  58.       containerOuter: 'choices',
  59.       containerInner: 'choices__inner',
  60.       input: 'choices__input',
  61.       inputCloned: 'choices__input--cloned',
  62.       list: 'choices__list',
  63.       listItems: 'choices__list--multiple',
  64.       listSingle: 'choices__list--single',
  65.       listDropdown: 'choices__list--dropdown',
  66.       item: 'choices__item',
  67.       itemSelectable: 'choices__item--selectable',
  68.       itemDisabled: 'choices__item--disabled',
  69.       itemChoice: 'choices__item--choice',
  70.       placeholder: 'choices__placeholder',
  71.       group: 'choices__group',
  72.       groupHeading: 'choices__heading',
  73.       button: 'choices__button',
  74.       activeState: 'is-active',
  75.       focusState: 'is-focused',
  76.       openState: 'is-open',
  77.       disabledState: 'is-disabled',
  78.       highlightedState: 'is-highlighted',
  79.       selectedState: 'is-selected',
  80.       flippedState: 'is-flipped',
  81.       loadingState: 'is-loading',
  82.       noResults: 'has-no-results',
  83.       noChoices: 'has-no-choices'
  84.     },
  85.     // Choices uses the great Fuse library for searching. You
  86.     // can find more options here: https://fusejs.io/api/options.html
  87.     fuseOptions: {
  88.       includeScore: true
  89.     },
  90.     labelId: '',
  91.     callbackOnInit: null,
  92.     callbackOnCreateTemplates: null
  93.   });
  94. ```

Terminology


WordDefinition
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ChoiceA
GroupA
ItemAn

Input Types


Choices works with the following input types, referenced in the documentation as noted.

HTMLDocumentation
-------------------------------------------------------------------------------------------------------|
[``text`
[``select-one`
[``select-multiple`

Configuration Options


silent


Type: Boolean Default: false

Input types affected: text, select-one, 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:

  1. ```
  2. [{
  3.   value: 'Value 1',
  4.   label: 'Label 1',
  5.   id: 1
  6. },
  7. {
  8.   value: 'Value 2',
  9.   label: 'Label 2',
  10.   id: 2,
  11.   customProperties: {
  12.     random: 'I am a custom property'
  13.   }
  14. }]
  15. ```

choices


Type: Array Default: []

Input types affected: select-one, select-multiple

Usage: Add choices (see terminology) to select input.

Pass an array of objects:

  1. ```
  2. [{
  3.   value: 'Option 1',
  4.   label: 'Option 1',
  5.   selected: true,
  6.   disabled: false,
  7. },
  8. {
  9.   value: 'Option 2',
  10.   label: 'Option 2',
  11.   selected: false,
  12.   disabled: true,
  13.   customProperties: {
  14.     description: 'Custom description about Option 2',
  15.     random: 'Another random custom property'
  16.   },
  17. }]
  18. ```

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.

allowHTML


Type: Boolean Default: true

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.

Deprecation Warning: This will default to false in a future release.

duplicateItemsAllowed


Type: Boolean Default: true

Input types affected: text, select-multiple

Usage: Whether duplicate inputted/chosen items are allowed

delimiter


Type: String Default: ,

Input types affected: text

Usage: What divides each value. The default delimiter separates 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.

addItemFilter


Type: string | RegExp | Function Default: 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:

  1. ``` js
  2. // Only adds items matching the text test
  3. new Choices(element, {
  4.   addItemFilter: (value) => {
  5.     return ['orange', 'apple', 'banana'].includes(value);
  6.   };
  7. });

  8. // only items ending to `-red`
  9. new Choices(element, {
  10.   addItemFilter: '-red$';
  11. });

  12. ```

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.

sorter


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:

  1. ``` js
  2. // Sorting via length of label from largest to smallest
  3. const example = new Choices(element, {
  4.   sorter: function(a, b) {
  5.     return b.label.length - a.label.length;
  6.   },
  7. };
  8. ```

placeholder


Type: Boolean Default: 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:

  1. ``` html
  2. <select>
  3.   <option value="">This is a placeholder</option>
  4.   <option>...</option>
  5.   <option>...</option>
  6.   <option>...</option>
  7. </select>
  8. ```

For backward compatibility, `` is also supported.

placeholderValue


Type: String Default: null

Input types affected: text

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-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 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. To access the max item count, pass a function with amaxItemCount argument (see the default config for an example), otherwise pass a string.

valueComparer


Type: Function Default: strict equality

Input types affected: select-one, select-multiple

Usage: A custom compare function used when finding choices by value (using setChoiceByValue).

Example:

  1. ``` js
  2. const example = new Choices(element, {
  3.   valueComparer: (a, b) => value.trim() === b.trim(),
  4. };
  5. ```

labelId


Type: String Default:

Input types affected: select-one, select-multiple

Usage: The labelId improves accessibility. If set, it will add aria-labelledby to the choices element.

classNames


Type: Object Default:

  1. ```
  2. classNames: {
  3.   containerOuter: 'choices',
  4.   containerInner: 'choices__inner',
  5.   input: 'choices__input',
  6.   inputCloned: 'choices__input--cloned',
  7.   list: 'choices__list',
  8.   listItems: 'choices__list--multiple',
  9.   listSingle: 'choices__list--single',
  10.   listDropdown: 'choices__list--dropdown',
  11.   item: 'choices__item',
  12.   itemSelectable: 'choices__item--selectable',
  13.   itemDisabled: 'choices__item--disabled',
  14.   itemOption: 'choices__item--choice',
  15.   group: 'choices__group',
  16.   groupHeading : 'choices__heading',
  17.   button: 'choices__button',
  18.   activeState: 'is-active',
  19.   focusState: 'is-focused',
  20.   openState: 'is-open',
  21.   disabledState: 'is-disabled',
  22.   highlightedState: 'is-highlighted',
  23.   selectedState: 'is-selected',
  24.   flippedState: 'is-flipped',
  25.   selectedState: 'is-highlighted',
  26. }
  27. ```

Input types affected: text, select-one, select-multiple

Usage: Classes added to HTML generated by Choices. By default classnames follow the BEM 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.
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.

Example:

  1. ``` js
  2. const example = new Choices(element, {
  3.   callbackOnCreateTemplates: () => ({
  4.     input: (...args) =>
  5.       Object.assign(Choices.defaults.templates.input.call(this, ...args), {
  6.         type: 'email',
  7.       }),
  8.   }),
  9. });
  10. ```

or more complex:

  1. ``` js
  2. const example = new Choices(element, {
  3.   callbackOnCreateTemplates: function(template) {
  4.     return {
  5.       item: ({ classNames }, data) => {
  6.         return template(`
  7.           <div class="${classNames.item} ${
  8.           data.highlighted
  9.             ? classNames.highlightedState
  10.             : classNames.itemSelectable
  11.         } ${
  12.           data.placeholder ? classNames.placeholder : ''
  13.         }" data-item data-id="${data.id}" data-value="${data.value}" ${
  14.           data.active ? 'aria-selected="true"' : ''
  15.         } ${data.disabled ? 'aria-disabled="true"' : ''}>
  16.             <span>&bigstar;</span> ${data.label}
  17.           </div>
  18.         `);
  19.       },
  20.       choice: ({ classNames }, data) => {
  21.         return template(`
  22.           <div class="${classNames.item} ${classNames.itemChoice} ${
  23.           data.disabled ? classNames.itemDisabled : classNames.itemSelectable
  24.         }" data-select-text="${this.config.itemSelectText}" data-choice ${
  25.           data.disabled
  26.             ? 'data-choice-disabled aria-disabled="true"'
  27.             : 'data-choice-selectable'
  28.         } data-id="${data.id}" data-value="${data.value}" ${
  29.           data.groupId > 0 ? 'role="treeitem"' : 'role="option"'
  30.         }>
  31.             <span>&bigstar;</span> ${data.label}
  32.           </div>
  33.         `);
  34.       },
  35.     };
  36.   },
  37. });
  38. ```

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.

Example:

  1. ``` js
  2. const element = document.getElementById('example');
  3. const example = new Choices(element);

  4. element.addEventListener(
  5.   'addItem',
  6.   function(event) {
  7.     // do something creative here...
  8.     console.log(event.detail.id);
  9.     console.log(event.detail.value);
  10.     console.log(event.detail.label);
  11.     console.log(event.detail.customProperties);
  12.     console.log(event.detail.groupValue);
  13.   },
  14.   false,
  15. );

  16. // or
  17. const example = new Choices(document.getElementById('example'));

  18. example.passedElement.element.addEventListener(
  19.   'addItem',
  20.   function(event) {
  21.     // do something creative here...
  22.     console.log(event.detail.id);
  23.     console.log(event.detail.value);
  24.     console.log(event.detail.label);
  25.     console.log(event.detail.customProperties);
  26.     console.log(event.detail.groupValue);
  27.   },
  28.   false,
  29. );
  30. ```

addItem


Payload: id, value, label, customProperties, groupValue, keyCode

Input types affected: text, select-one, select-multiple

Usage: Triggered each time an item is added (programmatically or by the user).

removeItem


Payload: id, value, label, customProperties, groupValue

Input types affected: text, select-one, select-multiple

Usage: Triggered each time an item is removed (programmatically or by the user).

highlightItem


Payload: id, value, label, groupValue

Input types affected: text, select-multiple

Usage: Triggered each time an item is highlighted.

unhighlightItem


Payload: id, value, label, groupValue

Input types affected: text, select-multiple

Usage: Triggered each time an item is unhighlighted.

choice


Payload: choice

Input types affected: select-one, select-multiple

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)

change


Payload: value

Input types affected: text, select-one, select-multiple

Usage: Triggered each time an item is added/removed by a user.

search


Payload: value, resultCount

Input types affected: select-one, select-multiple

Usage: Triggered when a user types into an input to search choices.

showDropdown


Payload: -

Input types affected: select-one, select-multiple

Usage: Triggered when the dropdown is shown.

hideDropdown


Payload: -

Input types affected: select-one, select-multiple

Usage: Triggered when the dropdown is hidden.

highlightChoice


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:

  1. ``` js
  2. // Calling a method by chaining
  3. const choices = new Choices(element, {
  4.   addItems: false,
  5.   removeItems: false,
  6. })
  7.   .setValue(['Set value 1', 'Set value 2'])
  8.   .disable();

  9. // Calling a method directly
  10. const choices = new Choices(element, {
  11.   addItems: false,
  12.   removeItems: false,
  13. });

  14. choices.setValue(['Set value 1', 'Set value 2']);
  15. choices.disable();
  16. ```

destroy();


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.

init();


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()).

highlightAll();


Input types affected: text, select-multiple

Usage: Highlight each chosen item (selected items can be removed).

unhighlightAll();


Input types affected: text, select-multiple

Usage: Un-highlight each chosen item.

removeActiveItemsByValue(value);


Input types affected: text, select-multiple

Usage: Remove each item by a given value.

removeActiveItems(excludedId);


Input types affected: text, select-multiple

Usage: Remove each selectable item.

removeHighlightedItems();


Input types affected: text, select-multiple

Usage: Remove each item the user has selected.

showDropdown();


Input types affected: select-one, select-multiple

Usage: Show option list dropdown (only affects select inputs).

hideDropdown();


Input types affected: text, select-multiple

Usage: Hide option list dropdown (only affects select inputs).

setChoices(choices, value, label, replaceChoices);


Input types affected: select-one, select-multiple

Usage: Set choices of select input via an array of objects (or function that returns array of object or promise of it), a value field name and a label field name.

This behaves the similar 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 3); 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).

Example 1:

  1. ``` js
  2. const example = new Choices(element);

  3. example.setChoices(
  4.   [
  5.     { value: 'One', label: 'Label One', disabled: true },
  6.     { value: 'Two', label: 'Label Two', selected: true },
  7.     { value: 'Three', label: 'Label Three' },
  8.   ],
  9.   'value',
  10.   'label',
  11.   false,
  12. );
  13. ```

Example 2:

  1. ``` js
  2. const example = new Choices(element);

  3. // Passing a function that returns Promise of choices
  4. example.setChoices(async () => {
  5.   try {
  6.     const items = await fetch('/items');
  7.     return items.json();
  8.   } catch (err) {
  9.     console.error(err);
  10.   }
  11. });
  12. ```

Example 3:

  1. ``` js
  2. const example = new Choices(element);

  3. example.setChoices(
  4.   [
  5.     {
  6.       label: 'Group one',
  7.       id: 1,
  8.       disabled: false,
  9.       choices: [
  10.         { value: 'Child One', label: 'Child One', selected: true },
  11.         { value: 'Child Two', label: 'Child Two', disabled: true },
  12.         { value: 'Child Three', label: 'Child Three' },
  13.       ],
  14.     },
  15.     {
  16.       label: 'Group two',
  17.       id: 2,
  18.       disabled: false,
  19.       choices: [
  20.         { value: 'Child Four', label: 'Child Four', disabled: true },
  21.         { value: 'Child Five', label: 'Child Five' },
  22.         {
  23.           value: 'Child Six',
  24.           label: 'Child Six',
  25.           customProperties: {
  26.             description: 'Custom description about child six',
  27.             random: 'Another random custom property',
  28.           },
  29.         },
  30.       ],
  31.     },
  32.   ],
  33.   'value',
  34.   'label',
  35.   false,
  36. );
  37. ```

clearChoices();


Input types affected: select-one, select-multiple

Usage: Clear all choices from select

getValue(valueOnly)


Input types affected: text, select-one, select-multiple

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.

Example:

  1. ``` js
  2. const example = new Choices(element);
  3. const values = example.getValue(true); // returns ['value 1', 'value 2'];
  4. 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'}];
  5. ```

setValue(items);


Input types affected: text

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.

Example:

  1. ``` js
  2. const example = new Choices(element);

  3. // via an array of objects
  4. example.setValue([
  5.   { value: 'One', label: 'Label One' },
  6.   { value: 'Two', label: 'Label Two' },
  7.   { value: 'Three', label: 'Label Three' },
  8. ]);

  9. // or via an array of strings
  10. example.setValue(['Four', 'Five', 'Six']);
  11. ```

setChoiceByValue(value);


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

Example:

  1. ``` js
  2. const example = new Choices(element, {
  3.   choices: [
  4.     { value: 'One', label: 'Label One' },
  5.     { value: 'Two', label: 'Label Two', disabled: true },
  6.     { value: 'Three', label: 'Label Three' },
  7.   ],
  8. });

  9. example.setChoiceByValue('Two'); // Choice with value of 'Two' has now been selected.
  10. ```

clearStore();


Input types affected: text, select-one, select-multiple

Usage: Removes all items, choices and groups. Use with caution.

clearInput();


Input types affected: text

Usage: Clear input of any user inputted text.

disable();


Input types affected: text, select-one, select-multiple

Usage: Disables input from accepting new value/selecting further choices.

enable();


Input types affected: text, select-one, select-multiple

Usage: Enables input to accept new values/select further choices.

Browser compatibility


Choices is compiled using Babel targeting browsers with more than 1% of global usage and expecting that features listed below are available or polyfilled in browser.
You may see exact list of target browsers by running npx browserslist within this repository folder.
If you need to support a browser that does not have one of the features listed below,
I suggest including a polyfill from the very good polyfill.io:

Polyfill example used for the demo:

  1. ``` html
  2. <script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=Array.from%2Ces5%2Ces6%2CSymbol%2CSymbol.iterator%2CDOMTokenList%2CObject.assign%2CCustomEvent%2CElement.prototype.classList%2CElement.prototype.closest%2CElement.prototype.dataset%2CArray.prototype.find%2CArray.prototype.includes"></script>
  3. ```

Features used in Choices:

  1. ```polyfills
  2. Array.from
  3. Array.prototype.find
  4. Array.prototype.includes
  5. Symbol
  6. Symbol.iterator
  7. DOMTokenList
  8. Object.assign
  9. CustomEvent
  10. Element.prototype.classList
  11. Element.prototype.closest
  12. Element.prototype.dataset
  13. ```

Development


To setup a local environment: clone this repo, navigate into its directory in a terminal window and run the following command:

npm install

NPM tasks


TaskUsage
-------------------------------------------------------------------------------------
`npmFire
`npmRun
`npmFire
`npmRun
`npmRun
`npmRun
`npmRun
`npmCompile
`npmWatch
`npmCompile,

Interested in contributing?


We're always interested in having more active maintainers.  Please get in touch if you're interested 👍

License


MIT License

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.

Misc


Thanks to @mikefrancis for sending me on a hunt for a non-jQuery solution for select boxes that eventually led to this being built!