Convert Figma logo to code with AI

Choices-js logoChoices

A vanilla JS customisable select box/text input plugin ⚡️

6,119
605
6,119
134

Top Related Projects

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

25,883

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

Selectize is the hybrid of a textbox and <select> box. It's jQuery based, and it has autocomplete and native-feeling keyboard navigation; useful for tagging, contact lists, etc.

21,849

Deprecated - Chosen is a library for making long, unwieldy select boxes more friendly.

Simple autocomplete pure vanilla Javascript library.

noUiSlider is a lightweight, ARIA-accessible JavaScript range slider with multi-touch and keyboard support. It is fully GPU animated: no reflows, so it is fast; even on older devices. It also fits wonderfully in responsive designs and has no dependencies.

Quick Overview

Choices.js is a lightweight, configurable select box/text input plugin. It's designed to enhance native HTML select and input elements with a customizable, searchable interface. The library is vanilla JavaScript with no dependencies, making it easy to integrate into various projects.

Pros

  • Lightweight and dependency-free
  • Highly customizable with numerous configuration options
  • Supports both single and multiple select inputs
  • Accessible, with ARIA attributes and keyboard navigation support

Cons

  • Limited styling options for some specific use cases
  • May require additional work to integrate with certain frameworks
  • Performance can degrade with very large datasets
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic single select:
const element = document.querySelector('.js-choice');
const choices = new Choices(element);
  1. Multiple select with custom options:
const element = document.querySelector('.js-choice');
const choices = new Choices(element, {
  removeItemButton: true,
  maxItemCount: 5,
  searchEnabled: true,
  searchPlaceholderValue: 'Search...'
});
  1. Adding and removing items programmatically:
const choices = new Choices(element);

// Add items
choices.setValue(['Option 1', 'Option 2']);

// Remove items
choices.removeActiveItems();

Getting Started

  1. Install Choices.js:
npm install choices.js
  1. Include the CSS and JS files in your HTML:
<link rel="stylesheet" href="path/to/choices.min.css">
<script src="path/to/choices.min.js"></script>
  1. Initialize Choices on your select or input element:
const element = document.querySelector('select');
const choices = new Choices(element, {
  // Options here
});
  1. Customize as needed using the available options and methods provided in the documentation.

Competitor Comparisons

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

Pros of Sortable

  • More versatile, allowing for drag-and-drop sorting of various elements, not just select options
  • Supports touch devices and works with mobile interfaces
  • Offers more advanced features like multi-list sorting and nested sortables

Cons of Sortable

  • Larger file size and potentially more complex to implement for simple use cases
  • May require more custom styling to achieve desired look and feel
  • Not specifically designed for enhancing select inputs, which is Choices' primary focus

Code Comparison

Choices (initializing a select input):

const element = document.querySelector('select');
const choices = new Choices(element, {
  searchEnabled: true,
  removeItemButton: true
});

Sortable (creating a sortable list):

const el = document.getElementById('items');
const sortable = Sortable.create(el, {
  animation: 150,
  ghostClass: 'blue-background-class'
});

While both libraries enhance user interaction, Choices focuses on improving select inputs with search and tagging capabilities, whereas Sortable provides drag-and-drop functionality for various elements. Choices is more suitable for form-based applications, while Sortable offers broader sorting capabilities across different types of content.

25,883

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

Pros of Select2

  • More mature and widely adopted, with a larger community and ecosystem
  • Extensive documentation and examples available
  • Better support for older browsers and jQuery integration

Cons of Select2

  • Heavier dependency on jQuery, which may not be ideal for modern projects
  • Larger file size and potentially slower performance compared to Choices
  • Less frequent updates and maintenance in recent years

Code Comparison

Select2:

$('#select-box').select2({
  placeholder: 'Select an option',
  allowClear: true,
  multiple: true
});

Choices:

const element = document.getElementById('select-box');
const choices = new Choices(element, {
  placeholder: true,
  removeItemButton: true,
  maxItemCount: -1
});

Both libraries offer similar functionality for enhancing select boxes, but Choices provides a more modern, vanilla JavaScript approach. Select2 relies on jQuery and offers a wider range of options out of the box, while Choices focuses on a lightweight, customizable solution with a smaller footprint.

Select2 is better suited for projects already using jQuery or requiring extensive browser support, whereas Choices is ideal for modern web applications prioritizing performance and minimal dependencies.

Selectize is the hybrid of a textbox and <select> box. It's jQuery based, and it has autocomplete and native-feeling keyboard navigation; useful for tagging, contact lists, etc.

Pros of selectize.js

  • More mature and established project with a larger community
  • Offers more advanced features like remote data loading and custom rendering
  • Better support for older browsers and legacy systems

Cons of selectize.js

  • Larger file size and potentially heavier performance impact
  • Less frequent updates and maintenance compared to Choices
  • Requires jQuery as a dependency

Code Comparison

Selectize.js:

$('#select-beast').selectize({
    create: true,
    sortField: 'text'
});

Choices:

const element = document.getElementById('choices-multiple-default');
const choices = new Choices(element, {
    removeItemButton: true
});

Key Differences

  • Selectize.js relies on jQuery, while Choices is a standalone vanilla JavaScript library
  • Choices has a more modern API and simpler setup process
  • Selectize.js offers more customization options but may require more configuration
  • Choices focuses on performance and modern browser support
  • Selectize.js has better support for server-side/remote data sources

Both libraries provide similar core functionality for enhancing select inputs, but they cater to different use cases and development preferences. Choices is better suited for modern web applications, while selectize.js might be preferred for projects with legacy requirements or those already using jQuery.

21,849

Deprecated - Chosen is a library for making long, unwieldy select boxes more friendly.

Pros of Chosen

  • Mature and well-established library with a large user base
  • Extensive browser compatibility, including older versions
  • Lightweight and simple to implement

Cons of Chosen

  • No longer actively maintained (last update in 2018)
  • Lacks modern features like keyboard navigation and accessibility options
  • Requires jQuery as a dependency

Code Comparison

Chosen (jQuery):

$(".my-select").chosen({
  disable_search_threshold: 10,
  no_results_text: "Oops, nothing found!",
  width: "95%"
});

Choices:

const element = document.querySelector('.my-select');
const choices = new Choices(element, {
  searchEnabled: false,
  searchResultLimit: 10,
  noResultsText: 'Oops, nothing found!',
  width: '95%'
});

Both libraries offer similar functionality for enhancing select inputs, but Choices is more modern and actively maintained. Chosen relies on jQuery and has a simpler API, while Choices is vanilla JavaScript with more advanced features. Choices provides better accessibility and keyboard navigation out of the box, making it more suitable for contemporary web applications. However, Chosen might be preferred for projects requiring support for older browsers or those already using jQuery extensively.

Simple autocomplete pure vanilla Javascript library.

Pros of autoComplete.js

  • Lightweight and fast, with a smaller file size
  • More flexible and customizable, allowing for complex search patterns
  • Better support for asynchronous data sources and API integrations

Cons of autoComplete.js

  • Less out-of-the-box styling options compared to Choices
  • Steeper learning curve for advanced customizations
  • Fewer built-in accessibility features

Code Comparison

autoComplete.js:

const autoCompleteJS = new autoComplete({
  selector: "#autoComplete",
  data: {
    src: ["Apple", "Banana", "Cherry"],
    cache: true,
  },
  resultsList: {
    element: (list, data) => {
      if (!data.results.length) {
        const message = document.createElement("div");
        message.setAttribute("class", "no_result");
        message.innerHTML = `<span>Found No Results for "${data.query}"</span>`;
        list.prepend(message);
      }
    },
    noResults: true,
  },
});

Choices:

const element = document.querySelector('.js-choice');
const choices = new Choices(element, {
  searchEnabled: true,
  searchChoices: true,
  itemSelectText: '',
  choices: [
    {value: 'Option 1', label: 'Option 1'},
    {value: 'Option 2', label: 'Option 2'},
    {value: 'Option 3', label: 'Option 3'},
  ],
});

Both libraries offer autocomplete functionality, but autoComplete.js provides more granular control over the search and result display process, while Choices offers a more straightforward setup with built-in styling options.

noUiSlider is a lightweight, ARIA-accessible JavaScript range slider with multi-touch and keyboard support. It is fully GPU animated: no reflows, so it is fast; even on older devices. It also fits wonderfully in responsive designs and has no dependencies.

Pros of noUiSlider

  • Lightweight and focused on range slider functionality
  • Highly customizable with extensive styling options
  • Supports touch devices and responsive design out of the box

Cons of noUiSlider

  • Limited to slider-based input, not suitable for other form elements
  • Requires more manual setup for advanced features like tooltips
  • Less built-in accessibility features compared to Choices

Code Comparison

noUiSlider:

var slider = document.getElementById('slider');
noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100
    }
});

Choices:

const element = document.getElementById('choices-multiple-default');
const choices = new Choices(element, {
    removeItemButton: true,
    maxItemCount: 5,
    searchResultLimit: 5,
    renderChoiceLimit: 5
});

noUiSlider focuses on creating range sliders with a simple API, while Choices provides a more comprehensive solution for various form inputs, including select boxes and text inputs. noUiSlider excels in creating customizable sliders, whereas Choices offers a broader range of input enhancements with built-in features like search and item limits.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Choices.js Actions Status Actions Status npm

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

Demo

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:

Sufficient Velocity

Wanderer Maps logo


Table of Contents

Installation

With NPM:

npm install choices.js

With Yarn:

yarn add choices.js

From a CDN:

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

<!-- Include base CSS (optional) -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/base.min.css"
/>
<!-- Or versioned -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/styles/base.min.css"
/>

<!-- Include Choices CSS -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"
/>
<!-- Or versioned -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/styles/choices.min.css"
/>

<!-- Include Choices JavaScript (latest) -->
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
<!-- Or versioned -->
<script src="https://cdn.jsdelivr.net/npm/choices.js@9.0.1/public/assets/scripts/choices.min.js"></script>

Or include Choices directly:

<!-- Include base CSS (optional) -->
<link rel="stylesheet" href="public/assets/styles/base.min.css" />
<!-- Include Choices CSS -->
<link rel="stylesheet" href="public/assets/styles/choices.min.css" />
<!-- Include Choices JavaScript -->
<script src="/public/assets/scripts/choices.min.js"></script>

CSS/SCSS

The use of import of css/scss is supported from webpack.

In .scss:

@import "choices.js/src/styles/choices";

In .js/.ts:

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.

  // 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]);

  // Passing options (with default options)
  const choices = new Choices(element, {
    silent: false,
    items: [],
    choices: [],
    renderChoiceLimit: -1,
    maxItemCount: -1,
    closeDropdownOnSelect: 'auto',
    singleModeForMultiSelect: false,
    addChoices: false,
    addItems: true,
    addItemFilter: (value) => !!value && value !== '',
    removeItems: true,
    removeItemButton: false,
    removeItemButtonAlignLeft: false,
    editItems: false,
    allowHTML: false,
    allowHtmlUserInput: false,
    duplicateItemsAllowed: true,
    delimiter: ',',
    paste: true,
    searchEnabled: true,
    searchChoices: true,
    searchFloor: 1,
    searchResultLimit: 4,
    searchFields: ['label', 'value'],
    position: 'auto',
    resetScrollPosition: true,
    shouldSort: true,
    shouldSortItems: false,
    sorter: () => {...},
    shadowRoot: null,
    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',
    uniqueItemText: 'Only unique values can be added',
    customAddItemText: 'Only values matching specific conditions can be added',
    addItemText: (value) => {
      return `Press Enter to add <b>"${value}"</b>`;
    },
    removeItemIconText: () => `Remove item`,
    removeItemLabelText: (value) => `Remove item: ${value}`,
    maxItemText: (maxItemCount) => {
      return `Only ${maxItemCount} values can be added`;
    },
    valueComparer: (value1, value2) => {
      return value1 === value2;
    },
    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'],
      description: ['choices__description'],
      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'],
      selectedState: ['is-selected'],
      flippedState: ['is-flipped'],
      loadingState: ['is-loading'],
      notice: ['choices__notice'],
      addChoice: ['choices__item--selectable', 'add-choice'],
      noResults: ['has-no-results'],
      noChoices: ['has-no-choices'],
    },
    // Choices uses the great Fuse library for searching. You
    // can find more options here: https://fusejs.io/api/options.html
    fuseOptions: {
      includeScore: true
    },
    labelId: '',
    callbackOnInit: null,
    callbackOnCreateTemplates: null,
    appendGroupInSearch: false,
  });

Terminology

WordDefinition
ChoiceA choice is a value a user can select. A choice would be equivalent to the <option></option> element within a select input.
GroupA group is a collection of choices. A group should be seen as equivalent to a <optgroup></optgroup> element within a select input.
ItemAn 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">

Input Types

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

HTML ElementDocumentation "Input Type"
<input type="text">text
<select>select-one
<select multiple>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:

[{
  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'
  },
},
{
  label: 'Group 1',
  choices: [{
    value: 'Option 3',
    label: 'Option 4',
    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).

closeDropdownOnSelect

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

singleModeForMultiSelect

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

addChoices

Type: Boolean Default: false

Input types affected: select-multiple, select-one

Usage: Whether a user can add choices dynamically.

Note: addItems must also be true

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.

removeItemButtonAlignLeft

Type: Boolean Default: false

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

Usage: Align item remove button left vs right

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: 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.

allowHtmlUserInput

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

duplicateItemsAllowed

Type: Boolean Default: true

Input types affected: text

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, select-multiple

Usage: Whether a search area should be shown.

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 ("-1" indicates no limit).

shadowRoot

Type: Document Element Default: null

Input types affected: select-one, select-multiple

Usage: You can pass along the shadowRoot from your application like so.

var shadowRoot = document
  .getElementById('wrapper')
  .attachShadow({ mode: 'open' });
...
var el = shadowRoot.querySelector(...);
var choices = new Choices(el, {
  shadowRoot: shadowRoot,
});

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:

// 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$';
});

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:

// 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;
  },
};

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:

<select data-placeholder="This is a placeholder">
  <option>...</option>
  <option>...</option>
  <option>...</option>
</select>

For backward compatibility, <option value="">This is a placeholder</option> and <option placeholder>This is a placeholder</option> are 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, 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.

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. Set to empty to not reserve space for this text.

addItemText

Type: String/Function Default: 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)

removeItemIconText

Type: String/Function Default: 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)

removeItemLabelText

Type: String/Function Default: 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)

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 a maxItemCount 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:

const example = new Choices(element, {
  valueComparer: (a, b) => value.trim() === b.trim(),
};

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:

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'],
  description: ['choices__description'],
  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'],
  selectedState: ['is-selected'],
  flippedState: ['is-flipped'],
  loadingState: ['is-loading'],
  notice: ['choices__notice'],
  addChoice: ['choices__item--selectable', 'add-choice'],
  noResults: ['has-no-results'],
  noChoices: ['has-no-choices'],
}

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(strToEl: (str: string) => HTMLElement, escapeForTemplate: (allowHTML: boolean, s: StringUntrusted | StringPreEscaped | string) => string, getClassNames: (s: Array | string) => string)

Type: Function Default: null Arguments: strToEl, escapeForTemplate

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.

@note For each callback, this refers to the current instance of Choices. This can be useful if you need access to methods (this.disable()).

Example:

const example = new Choices(element, {
  callbackOnCreateTemplates: (strToEl, escapeForTemplate, getClassNames) => ({
    input: (...args) =>
      Object.assign(Choices.defaults.templates.input.call(this, ...args), {
        type: 'email',
      }),
  }),
});

or more complex:

const example = new Choices(element, {
  callbackOnCreateTemplates: function(strToEl, escapeForTemplate, getClassNames) {
    return {
      item: ({ classNames }, data) => {
        return template(`
          <div class="${getClassNames(classNames.item).join(' ')} ${
          getClassNames(data.highlighted
            ? classNames.highlightedState
            : classNames.itemSelectable).join(' ')
        } ${
          data.placeholder ? classNames.placeholder : ''
        }" data-item data-id="${data.id}" data-value="${escapeForTemplate(data.value)}" ${
          data.active ? 'aria-selected="true"' : ''
        } ${data.disabled ? 'aria-disabled="true"' : ''}>
            <span>&bigstar;</span> ${escapeForTemplate(data.label)}
          </div>
        `);
      },
      choice: ({ classNames }, data) => {
        return template(`
          <div class="${getClassNames(classNames.item).join(' ')} ${getClassNames(classNames.itemChoice).join(' ')} ${
          getClassNames(data.disabled ? classNames.itemDisabled : classNames.itemSelectable).join(' ')
        }" 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="${escapeForTemplate(data.value)}" ${
          data.groupId > 0 ? 'role="treeitem"' : 'role="option"'
        }>
            <span>&bigstar;</span> ${escapeForTemplate(data.label)}
          </div>
        `);
      },
    };
  },
});

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:

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);
    console.log(event.detail.label);
    console.log(event.detail.customProperties);
    console.log(event.detail.groupValue);
  },
  false,
);

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

example.passedElement.element.addEventListener(
  'addItem',
  function(event) {
    // do something creative here...
    console.log(event.detail.id);
    console.log(event.detail.value);
    console.log(event.detail.label);
    console.log(event.detail.customProperties);
    console.log(event.detail.groupValue);
  },
  false,
);

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: string

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

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

search

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.

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:

// 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();

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

refresh(withEvents: boolean = false, selectFirstOption: boolean = false);

Input types affected: select-multiple, select-one

Usage: Reads options from backing <select> element, and recreates choices. Existing items are preserved. When withEvents is truthy, only addItem events are generated.

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: string);

Input types affected: text, select-multiple

Usage: Remove each item by a given value.

removeActiveItems(excludedId?: number);

Input types affected: text, select-multiple

Usage: Remove each selectable item.

removeChoice(value: string);

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

Usage: Remove an option/item by value

removeHighlightedItems(runEvent?: boolean);

Input types affected: text, select-multiple

Usage: Remove each item the user has selected.

showDropdown(preventInputFocus?: boolean);

Input types affected: select-one, select-multiple

Usage: Show choices list dropdown.

hideDropdown(preventInputFocus?: boolean);

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

Usage: Hide choices list dropdown.

setChoices(choicesArrayOrFetcher?: (InputChoice | InputGroup)[] | ((instance: Choices) => (InputChoice | InputGroup)[] | Promise<(InputChoice | InputGroup)[]>), value?: string | null, label?: string, replaceChoices?: boolean): this | Promise;

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:

const example = new Choices(element);

example.setChoices(
  [
    { value: 'One', label: 'Label One', disabled: true },
    { value: 'Two', label: 'Label Two', selected: true },
    { value: 'Three', label: 'Label Three' },
  ],
  'value',
  'label',
  false,
);

Example 2:

const example = new Choices(element);

// Passing a function that returns Promise of choices
example.setChoices(async () => {
  try {
    const items = await fetch('/items');
    return items.json();
  } catch (err) {
    console.error(err);
  }
});

Example 3:

const example = new Choices(element);

example.setChoices(
  [
    {
      label: 'Group one',
      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' },
      ],
    },
    {
      label: 'Group two',
      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',
          },
        },
      ],
    },
  ],
  'value',
  'label',
  false,
);

clearChoices();

Input types affected: select-one, select-multiple

Usage: Clear all choices from select. Does not reset the search state.

getValue(valueOnly?: boolean): string[] | EventChoice[] | EventChoice | string;

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:

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(items: string[] | InputChoice[]): this;

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

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:

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' },
]);

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

setChoiceByValue(value: string | string[]);

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:

const example = new Choices(element, {
  choices: [
    { value: 'One', label: 'Label One' },
    { value: 'Two', label: 'Label Two', disabled: true },
    { value: 'Three', label: 'Label Three' },
  ],
});

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

clearStore();

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

Usage: Removes all items, choices and groups. Resets the search state. 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 npm exec 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 cdnjs.cloudflare.com/polyfill:

Polyfill example used for the demo:

<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0&features=Array.from%2CArray.prototype.find%2CArray.prototype.includes%2CSymbol%2CSymbol.iterator%2CDOMTokenList%2CObject.assign%2CCustomEvent%2CElement.prototype.classList%2CElement.prototype.closest%2CElement.prototype.dataset%2CElement.prototype.replaceChildren"></script>

Features used in Choices:

Array.from
Array.prototype.find
Array.prototype.includes
Symbol
Symbol.iterator
DOMTokenList
Object.assign
CustomEvent
Element.prototype.classList
Element.prototype.closest
Element.prototype.dataset
Element.prototype.replaceChildren

Development

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

npm install

playwright

e2e (End-to-end) tests are implemented using playwright, which requires installing likely with OS support.

npx playwright install npx playwright install-deps

For JetBrain IDE's the Test automation plugin is recommended: https://www.jetbrains.com/help/phpstorm/playwright.html

NPM tasks

TaskUsage
npm run startFire up local server for development
npm run test:unitRun sequence of tests once
npm run test:unit:watchFire up test server and re-test on file change
npm run test:e2eRun sequence of e2e tests (with local server)
npm run testRun both unit and e2e tests
npm run playwright:guiRun Playwright e2e tests (GUI)
npm run playwright:cliRun Playwright e2e tests (CLI)
npm run js:buildCompile Choices to an uglified JavaScript file
npm run css:watchWatch SCSS files for changes. On a change, run build process
npm run css:buildCompile, minify and prefix SCSS files to CSS

Build flags

Choices supports various environment variables as build-flags to enable/disable features. The pre-built bundles these features set, and tree shaking uses the non-used parts.

CHOICES_SEARCH_FUSE

Values: full / basic / null Default: full

Fuse.js support a full/basic profile. full adds additional logic operations, which aren't used by default with Choices. The null option drops Fuse.js as a dependency and instead uses a simple prefix only search feature.

CHOICES_CAN_USE_DOM

Values: 1 / 0 Default: 1

Allows loading Choices into a non-browser environment.

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!

NPM DownloadsLast 30 Days