choices.js

  • Version 11.1.0
  • Published
  • 1.92 MB
  • 1 dependency
  • MIT license

Install

npm i choices.js
yarn add choices.js
pnpm add choices.js

Overview

A vanilla JS customisable text input/select box plugin

Index

Variables

Classes

Interfaces

Type Aliases

Namespaces

Variables

variable ActionType

const ActionType: {
readonly ADD_CHOICE: 'ADD_CHOICE';
readonly REMOVE_CHOICE: 'REMOVE_CHOICE';
readonly FILTER_CHOICES: 'FILTER_CHOICES';
readonly ACTIVATE_CHOICES: 'ACTIVATE_CHOICES';
readonly CLEAR_CHOICES: 'CLEAR_CHOICES';
readonly ADD_GROUP: 'ADD_GROUP';
readonly ADD_ITEM: 'ADD_ITEM';
readonly REMOVE_ITEM: 'REMOVE_ITEM';
readonly HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM';
};

    variable DEFAULT_CLASSNAMES

    const DEFAULT_CLASSNAMES: ClassNames;

      variable DEFAULT_CONFIG

      const DEFAULT_CONFIG: Options;

        variable EventType

        const EventType: {
        readonly showDropdown: 'showDropdown';
        readonly hideDropdown: 'hideDropdown';
        readonly change: 'change';
        readonly choice: 'choice';
        readonly search: 'search';
        readonly addItem: 'addItem';
        readonly removeItem: 'removeItem';
        readonly highlightItem: 'highlightItem';
        readonly highlightChoice: 'highlightChoice';
        readonly unhighlightItem: 'unhighlightItem';
        };

          variable KeyCodeMap

          const KeyCodeMap: {
          readonly TAB_KEY: 9;
          readonly SHIFT_KEY: 16;
          readonly BACK_KEY: 46;
          readonly DELETE_KEY: 8;
          readonly ENTER_KEY: 13;
          readonly A_KEY: 65;
          readonly ESC_KEY: 27;
          readonly UP_KEY: 38;
          readonly DOWN_KEY: 40;
          readonly PAGE_UP_KEY: 33;
          readonly PAGE_DOWN_KEY: 34;
          };

            variable ObjectsInConfig

            const ObjectsInConfig: string[];

              variable PassedElementTypes

              const PassedElementTypes: {
              readonly Text: 'text';
              readonly SelectOne: 'select-one';
              readonly SelectMultiple: 'select-multiple';
              };

                variable SCROLLING_SPEED

                const SCROLLING_SPEED: number;

                  variable templates

                  const templates: TemplatesInterface;

                    Classes

                    class Choices

                    class Choices {}
                    • Choices Josh Johnson<josh@joshuajohnson.co.uk>

                    constructor

                    constructor(
                    element?: string | Element | HTMLInputElement | HTMLSelectElement,
                    userConfig?: Partial<Options>
                    );

                      property choiceList

                      choiceList: List;

                        property config

                        config: Options;

                          property containerInner

                          containerInner: Container;

                            property containerOuter

                            containerOuter: Container;

                              property defaults

                              static readonly defaults: {
                              options: Partial<Options>;
                              allOptions: Options;
                              templates: Templates;
                              };

                                property dropdown

                                dropdown: Dropdown;

                                  property initialised

                                  initialised: boolean;

                                    property initialisedOK

                                    initialisedOK?: boolean;

                                      property input

                                      input: Input;

                                        property itemList

                                        itemList: List;

                                          property passedElement

                                          passedElement: WrappedInput | WrappedSelect;

                                            property version

                                            static version: string;

                                              method clearChoices

                                              clearChoices: (clearOptions?: boolean, clearItems?: boolean) => this;

                                                method clearInput

                                                clearInput: () => this;

                                                  method clearStore

                                                  clearStore: (clearOptions?: boolean) => this;

                                                    method destroy

                                                    destroy: () => void;

                                                      method disable

                                                      disable: () => this;

                                                        method enable

                                                        enable: () => this;

                                                          method getValue

                                                          getValue: <B extends boolean = false>(
                                                          valueOnly?: B
                                                          ) => EventChoiceValueType<B> | EventChoiceValueType<B>[];

                                                            method hideDropdown

                                                            hideDropdown: (preventInputBlur?: boolean) => this;

                                                              method highlightAll

                                                              highlightAll: () => this;

                                                                method highlightItem

                                                                highlightItem: (item: InputChoice, runEvent?: boolean) => this;

                                                                  method init

                                                                  init: () => void;

                                                                    method refresh

                                                                    refresh: (
                                                                    withEvents?: boolean,
                                                                    selectFirstOption?: boolean,
                                                                    deselectAll?: boolean
                                                                    ) => this;

                                                                      method removeActiveItems

                                                                      removeActiveItems: (excludedId?: number) => this;

                                                                        method removeActiveItemsByValue

                                                                        removeActiveItemsByValue: (value: string) => this;

                                                                          method removeChoice

                                                                          removeChoice: (value: string) => this;

                                                                            method removeHighlightedItems

                                                                            removeHighlightedItems: (runEvent?: boolean) => this;

                                                                              method setChoiceByValue

                                                                              setChoiceByValue: (value: string | string[]) => this;

                                                                                method setChoices

                                                                                setChoices: (
                                                                                choicesArrayOrFetcher?:
                                                                                | (InputChoice | InputGroup)[]
                                                                                | ((
                                                                                instance: Choices
                                                                                ) =>
                                                                                | (InputChoice | InputGroup)[]
                                                                                | Promise<(InputChoice | InputGroup)[]>),
                                                                                value?: string | null,
                                                                                label?: string,
                                                                                replaceChoices?: boolean,
                                                                                clearSearchFlag?: boolean,
                                                                                replaceItems?: boolean
                                                                                ) => this | Promise<this>;
                                                                                • 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 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).

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

                                                                                  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);
                                                                                  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',
                                                                                  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'},
                                                                                  ]
                                                                                  },
                                                                                  {
                                                                                  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'
                                                                                  }},
                                                                                  ]
                                                                                  }], 'value', 'label', false);

                                                                                method setValue

                                                                                setValue: (items: string[] | InputChoice[]) => this;

                                                                                  method showDropdown

                                                                                  showDropdown: (preventInputFocus?: boolean) => this;

                                                                                    method unhighlightAll

                                                                                    unhighlightAll: () => this;

                                                                                      method unhighlightItem

                                                                                      unhighlightItem: (item: InputChoice, runEvent?: boolean) => this;

                                                                                        Interfaces

                                                                                        interface Choice

                                                                                        interface Choice extends InputChoice {}
                                                                                        • Deprecated

                                                                                          Use InputChoice instead

                                                                                        interface ClassNames

                                                                                        interface ClassNames {}
                                                                                        • Classes added to HTML generated by By default classnames follow the BEM notation.

                                                                                        property activeState

                                                                                        activeState: string | Array<string>;
                                                                                        • ['is-active']

                                                                                        property addChoice

                                                                                        addChoice: string | Array<string>;
                                                                                        • ['choices__item--selectable', 'add-choice']

                                                                                        property button

                                                                                        button: string | Array<string>;
                                                                                        • ['choices__button']

                                                                                        property containerInner

                                                                                        containerInner: string | Array<string>;
                                                                                        • ['choices__inner']

                                                                                        property containerOuter

                                                                                        containerOuter: string | Array<string>;
                                                                                        • ['choices']

                                                                                        property description

                                                                                        description: string | Array<string>;
                                                                                        • ['choices__description']

                                                                                        property disabledState

                                                                                        disabledState: string | Array<string>;
                                                                                        • ['is-disabled']

                                                                                        property flippedState

                                                                                        flippedState: string | Array<string>;
                                                                                        • ['is-flipped']

                                                                                        property focusState

                                                                                        focusState: string | Array<string>;
                                                                                        • ['is-focused']

                                                                                        property group

                                                                                        group: string | Array<string>;
                                                                                        • ['choices__group']

                                                                                        property groupHeading

                                                                                        groupHeading: string | Array<string>;
                                                                                        • ['choices__heading']

                                                                                        property highlightedState

                                                                                        highlightedState: string | Array<string>;
                                                                                        • ['is-highlighted']

                                                                                        property input

                                                                                        input: string | Array<string>;
                                                                                        • ['choices__input']

                                                                                        property inputCloned

                                                                                        inputCloned: string | Array<string>;
                                                                                        • ['choices__input--cloned']

                                                                                        property item

                                                                                        item: string | Array<string>;
                                                                                        • ['choices__item']

                                                                                        property itemChoice

                                                                                        itemChoice: string | Array<string>;
                                                                                        • ['choices__item--choice']

                                                                                        property itemDisabled

                                                                                        itemDisabled: string | Array<string>;
                                                                                        • ['choices__item--disabled']

                                                                                        property itemSelectable

                                                                                        itemSelectable: string | Array<string>;
                                                                                        • ['choices__item--selectable']

                                                                                        property list

                                                                                        list: string | Array<string>;
                                                                                        • ['choices__list']

                                                                                        property listDropdown

                                                                                        listDropdown: string | Array<string>;
                                                                                        • ['choices__list--dropdown']

                                                                                        property listItems

                                                                                        listItems: string | Array<string>;
                                                                                        • ['choices__list--multiple']

                                                                                        property listSingle

                                                                                        listSingle: string | Array<string>;
                                                                                        • ['choices__list--single']

                                                                                        property loadingState

                                                                                        loadingState: string | Array<string>;
                                                                                        • ['is-loading']

                                                                                        property noChoices

                                                                                        noChoices: string | Array<string>;
                                                                                        • ['has-no-choices']

                                                                                        property noResults

                                                                                        noResults: string | Array<string>;
                                                                                        • ['has-no-results']

                                                                                        property notice

                                                                                        notice: string | Array<string>;
                                                                                        • ['choices__notice']

                                                                                        property openState

                                                                                        openState: string | Array<string>;
                                                                                        • ['is-open']

                                                                                        property placeholder

                                                                                        placeholder: string | Array<string>;
                                                                                        • ['choices__placeholder']

                                                                                        property selectedState

                                                                                        selectedState: string | Array<string>;
                                                                                        • ['is-selected']

                                                                                        interface EventChoice

                                                                                        interface EventChoice extends InputChoice {}

                                                                                          property element

                                                                                          element?: HTMLOptionElement | HTMLOptGroupElement;

                                                                                            property groupValue

                                                                                            groupValue?: string;

                                                                                              property keyCode

                                                                                              keyCode?: number;

                                                                                                interface EventMap

                                                                                                interface EventMap {}
                                                                                                • 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.

                                                                                                property addItem

                                                                                                addItem: CustomEvent<EventChoice>;
                                                                                                • Triggered each time an item is added (programmatically or by the user).

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

                                                                                                  Arguments: id, value, label, groupValue

                                                                                                property change

                                                                                                change: CustomEvent<{
                                                                                                value: string;
                                                                                                }>;
                                                                                                • Triggered each time an item is added/removed **by a user**.

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

                                                                                                  Arguments: value

                                                                                                property choice

                                                                                                choice: CustomEvent<{
                                                                                                choice: InputChoice;
                                                                                                }>;
                                                                                                • Triggered each time a choice is selected **by a user**, regardless if it changes the value of the input.

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

                                                                                                  Arguments: choice: Choice

                                                                                                property hideDropdown

                                                                                                hideDropdown: CustomEvent<undefined>;
                                                                                                • Triggered when the dropdown is hidden.

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

                                                                                                  Arguments: -

                                                                                                property highlightChoice

                                                                                                highlightChoice: CustomEvent<{
                                                                                                el: HTMLElement;
                                                                                                }>;
                                                                                                • Triggered when a choice from the dropdown is highlighted.

                                                                                                  Input types affected: select-one, select-multiple Arguments: el is the choice.passedElement that was affected.

                                                                                                property highlightItem

                                                                                                highlightItem: CustomEvent<EventChoice | undefined>;
                                                                                                • Triggered each time an item is highlighted.

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

                                                                                                  Arguments: id, value, label, groupValue

                                                                                                property removeItem

                                                                                                removeItem: CustomEvent<EventChoice | undefined>;
                                                                                                • Triggered each time an item is removed (programmatically or by the user).

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

                                                                                                  Arguments: id, value, label, groupValue

                                                                                                property search

                                                                                                search: CustomEvent<{
                                                                                                value: string;
                                                                                                resultCount: number;
                                                                                                }>;
                                                                                                • 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.

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

                                                                                                  Arguments: value, resultCount

                                                                                                property showDropdown

                                                                                                showDropdown: CustomEvent<undefined>;
                                                                                                • Triggered when the dropdown is shown.

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

                                                                                                  Arguments: -

                                                                                                property unhighlightItem

                                                                                                unhighlightItem: CustomEvent<EventChoice | undefined>;
                                                                                                • Triggered each time an item is unhighlighted.

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

                                                                                                  Arguments: id, value, label, groupValue

                                                                                                interface Group

                                                                                                interface Group extends InputGroup {}
                                                                                                • Deprecated

                                                                                                  Use InputGroup instead

                                                                                                interface InputChoice

                                                                                                interface InputChoice {}

                                                                                                  property active

                                                                                                  active?: boolean;

                                                                                                    property customProperties

                                                                                                    customProperties?: Types.CustomProperties;

                                                                                                      property disabled

                                                                                                      disabled?: boolean;

                                                                                                        property highlighted

                                                                                                        highlighted?: boolean;

                                                                                                          property id

                                                                                                          id?: number;

                                                                                                            property label

                                                                                                            label: StringUntrusted | string;

                                                                                                              property labelClass

                                                                                                              labelClass?: string | Array<string>;

                                                                                                                property labelDescription

                                                                                                                labelDescription?: string;

                                                                                                                  property placeholder

                                                                                                                  placeholder?: boolean;

                                                                                                                    property selected

                                                                                                                    selected?: boolean;

                                                                                                                      property value

                                                                                                                      value: any;

                                                                                                                        interface InputGroup

                                                                                                                        interface InputGroup {}

                                                                                                                          property active

                                                                                                                          active?: boolean;

                                                                                                                            property choices

                                                                                                                            choices: InputChoice[];

                                                                                                                              property disabled

                                                                                                                              disabled?: boolean;

                                                                                                                                property id

                                                                                                                                id?: number;

                                                                                                                                  property label

                                                                                                                                  label?: StringUntrusted | string;

                                                                                                                                    property value

                                                                                                                                    value: string;

                                                                                                                                      interface Item

                                                                                                                                      interface Item extends InputChoice {}
                                                                                                                                      • Deprecated

                                                                                                                                        Use InputChoice instead

                                                                                                                                      interface Options

                                                                                                                                      interface Options {}
                                                                                                                                      • Choices options interface

                                                                                                                                        **Terminology**

                                                                                                                                        - **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. - **Item:** An item is an inputted value **_(text input)_** or a selected choice **_(select element)_**. In the context of a select element, an item is equivelent to a selected option element: <option value="Hello" selected></option> whereas in the context of a text input an item is equivelant to <input type="text" value="Hello">

                                                                                                                                      property addChoices

                                                                                                                                      addChoices: boolean;
                                                                                                                                      • Whether a user can add choices dynamically.

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

                                                                                                                                        false

                                                                                                                                      property addItemFilter

                                                                                                                                      addItemFilter: string | RegExp | Types.FilterFunction | null;
                                                                                                                                      • A filter that will need to pass for a user to successfully add an item.

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

                                                                                                                                        (value) => !!value && value !== ''

                                                                                                                                      property addItems

                                                                                                                                      addItems: boolean;
                                                                                                                                      • Whether a user can add items.

                                                                                                                                        **Input types affected:** text

                                                                                                                                        true

                                                                                                                                      property addItemText

                                                                                                                                      addItemText: string | Types.NoticeStringFunction;
                                                                                                                                      • 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. The raw non-sanitised value is passed as a 2nd argument.

                                                                                                                                        Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)

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

                                                                                                                                        (value, valueRaw) => `Press Enter to add <b>"${value}"</b>`;

                                                                                                                                      property allowHTML

                                                                                                                                      allowHTML: boolean;
                                                                                                                                      • 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.

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

                                                                                                                                        false

                                                                                                                                      property allowHtmlUserInput

                                                                                                                                      allowHtmlUserInput: boolean;
                                                                                                                                      • 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 previously submitted choices from a remote source.

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

                                                                                                                                        false

                                                                                                                                      property appendGroupInSearch

                                                                                                                                      appendGroupInSearch: false;

                                                                                                                                        property appendValue

                                                                                                                                        appendValue: string | null;
                                                                                                                                        • Append a value to each item added/selected.

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

                                                                                                                                          null

                                                                                                                                        property callbackOnCreateTemplates

                                                                                                                                        callbackOnCreateTemplates: CallbackOnCreateTemplatesFn | null;
                                                                                                                                        • Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined here [https://github.com/jshjohnson/Choices/blob/67f29c286aa21d88847adfcd6304dc7d068dc01f/assets/scripts/src/choices.js#L1993-L2067].

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

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

                                                                                                                                          Example 1

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

                                                                                                                                          null

                                                                                                                                        property callbackOnInit

                                                                                                                                        callbackOnInit: (() => void) | null;
                                                                                                                                        • Function to run once Choices initialises.

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

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

                                                                                                                                          null

                                                                                                                                        property choices

                                                                                                                                        choices: InputChoice[];
                                                                                                                                        • Add choices (see terminology) to select input.

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

                                                                                                                                          Example 1

                                                                                                                                          [{
                                                                                                                                          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'
                                                                                                                                          }
                                                                                                                                          }]
                                                                                                                                          }]

                                                                                                                                          []

                                                                                                                                        property classNames

                                                                                                                                        classNames: ClassNames;
                                                                                                                                        • Classes added to HTML generated by By default classnames follow the BEM notation.

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

                                                                                                                                        property closeDropdownOnSelect

                                                                                                                                        closeDropdownOnSelect: boolean | 'auto';
                                                                                                                                        • 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

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

                                                                                                                                          'auto'

                                                                                                                                        property customAddItemText

                                                                                                                                        customAddItemText: string | Types.NoticeStringFunction;
                                                                                                                                        • The text that is shown when addItemFilter is passed and it returns false

                                                                                                                                          Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)

                                                                                                                                          **Input types affected:** text

                                                                                                                                          'Only values matching specific conditions can be added'

                                                                                                                                        property delimiter

                                                                                                                                        delimiter: string;
                                                                                                                                        • What divides each value. The default delimiter separates each value with a comma: "Value 1, Value 2, Value 3".

                                                                                                                                          **Input types affected:** text

                                                                                                                                          ','

                                                                                                                                        property duplicateItemsAllowed

                                                                                                                                        duplicateItemsAllowed: boolean;
                                                                                                                                        • Whether each inputted/chosen item should be unique.

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

                                                                                                                                          true

                                                                                                                                        property editItems

                                                                                                                                        editItems: boolean;
                                                                                                                                        • Whether a user can edit items. An item's value can be edited by pressing the backspace.

                                                                                                                                          **Input types affected:** text

                                                                                                                                          false

                                                                                                                                        property fuseOptions

                                                                                                                                        fuseOptions: IFuseOptions<unknown>;
                                                                                                                                        • Choices uses the great Fuse library for searching. You can find more options here: https://fusejs.io/api/options.html

                                                                                                                                        property items

                                                                                                                                        items: string[] | InputChoice[];
                                                                                                                                        • Add pre-selected items (see terminology) to text input.

                                                                                                                                          **Input types affected:** text

                                                                                                                                          Example 1

                                                                                                                                          ['value 1', 'value 2', 'value 3']

                                                                                                                                          Example 2

                                                                                                                                          [{
                                                                                                                                          value: 'Value 1',
                                                                                                                                          label: 'Label 1',
                                                                                                                                          id: 1
                                                                                                                                          },
                                                                                                                                          {
                                                                                                                                          value: 'Value 2',
                                                                                                                                          label: 'Label 2',
                                                                                                                                          id: 2,
                                                                                                                                          customProperties: {
                                                                                                                                          random: 'I am a custom property'
                                                                                                                                          }
                                                                                                                                          }]

                                                                                                                                          []

                                                                                                                                        property itemSelectText

                                                                                                                                        itemSelectText: string;
                                                                                                                                        • The text that is shown when a user hovers over a selectable choice. Set to empty to not reserve space for this text.

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

                                                                                                                                          'Press to select'

                                                                                                                                        property labelId

                                                                                                                                        labelId: string;
                                                                                                                                        • ID of the connected label to improve a11y. If set, aria-labelledby will be added.

                                                                                                                                        property loadingText

                                                                                                                                        loadingText: string;
                                                                                                                                        • The text that is shown whilst choices are being populated via AJAX.

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

                                                                                                                                          'Loading...'

                                                                                                                                        property maxItemCount

                                                                                                                                        maxItemCount: number;
                                                                                                                                        • The amount of items a user can input/select ("-1" indicates no limit).

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

                                                                                                                                          -1

                                                                                                                                        property maxItemText

                                                                                                                                        maxItemText: string | Types.NoticeLimitFunction;
                                                                                                                                        • 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.

                                                                                                                                          **Input types affected:** text

                                                                                                                                          (maxItemCount) => `Only ${maxItemCount} values can be added.`;

                                                                                                                                        property noChoicesText

                                                                                                                                        noChoicesText: string | Types.StringFunction;
                                                                                                                                        • The text that is shown when a user has selected all possible choices, or no choices exist. Optionally pass a function returning a string.

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

                                                                                                                                          'No choices to choose from'

                                                                                                                                        property noResultsText

                                                                                                                                        noResultsText: string | Types.StringFunction;
                                                                                                                                        • The text that is shown when a user's search has returned no results. Optionally pass a function returning a string.

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

                                                                                                                                          'No results found'

                                                                                                                                        property paste

                                                                                                                                        paste: boolean;
                                                                                                                                        • Whether a user can paste into the input.

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

                                                                                                                                          true

                                                                                                                                        property placeholder

                                                                                                                                        placeholder: boolean;
                                                                                                                                        • 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.

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

                                                                                                                                          For single 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>

                                                                                                                                          true

                                                                                                                                        property placeholderValue

                                                                                                                                        placeholderValue: string | null;
                                                                                                                                        • The value of the inputs placeholder.

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

                                                                                                                                          null

                                                                                                                                        property position

                                                                                                                                        position: PositionOptionsType;
                                                                                                                                        • 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.

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

                                                                                                                                          'auto'

                                                                                                                                        property prependValue

                                                                                                                                        prependValue: string | null;
                                                                                                                                        • Prepend a value to each item added/selected.

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

                                                                                                                                          null

                                                                                                                                        property removeItemButton

                                                                                                                                        removeItemButton: boolean;
                                                                                                                                        • Whether each item should have a remove button.

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

                                                                                                                                          false

                                                                                                                                        property removeItemButtonAlignLeft

                                                                                                                                        removeItemButtonAlignLeft: boolean;
                                                                                                                                        • Align item remove button left vs right.

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

                                                                                                                                          false

                                                                                                                                        property removeItemIconText

                                                                                                                                        removeItemIconText: string | Types.NoticeStringFunction;
                                                                                                                                        • 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. The raw non-sanitised value is passed as a 2nd argument.

                                                                                                                                          Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)

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

                                                                                                                                          (value, valueRaw) => `Remove item`;

                                                                                                                                        property removeItemLabelText

                                                                                                                                        removeItemLabelText: string | Types.NoticeStringFunction;
                                                                                                                                        • 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. The raw non-sanitised value is passed as a 2nd argument.

                                                                                                                                          Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)

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

                                                                                                                                          (value, valueRaw) => `Remove item: ${value}`;

                                                                                                                                        property removeItems

                                                                                                                                        removeItems: boolean;
                                                                                                                                        • Whether a user can remove items.

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

                                                                                                                                          true

                                                                                                                                        property renderChoiceLimit

                                                                                                                                        renderChoiceLimit: number;
                                                                                                                                        • 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.

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

                                                                                                                                          -1

                                                                                                                                        property renderSelectedChoices

                                                                                                                                        renderSelectedChoices: 'auto' | 'always' | boolean;
                                                                                                                                        • 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.

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

                                                                                                                                          'auto';

                                                                                                                                        property resetScrollPosition

                                                                                                                                        resetScrollPosition: boolean;
                                                                                                                                        • Whether the scroll position should reset after adding an item.

                                                                                                                                          **Input types affected:** select-multiple

                                                                                                                                          true

                                                                                                                                        property searchChoices

                                                                                                                                        searchChoices: boolean;
                                                                                                                                        • Whether choices should be filtered by input or not. If false, the search event will still emit, but choices will not be filtered.

                                                                                                                                          **Input types affected:** select-one

                                                                                                                                          true

                                                                                                                                        property searchEnabled

                                                                                                                                        searchEnabled: boolean;
                                                                                                                                        • Whether a search area should be shown.

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

                                                                                                                                          true

                                                                                                                                        property searchFields

                                                                                                                                        searchFields: string[];
                                                                                                                                        • 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'].

                                                                                                                                          Input types affected:select-one, select-multiple

                                                                                                                                          ['label', 'value']

                                                                                                                                        property searchFloor

                                                                                                                                        searchFloor: number;
                                                                                                                                        • The minimum length a search value should be before choices are searched.

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

                                                                                                                                          1

                                                                                                                                        property searchPlaceholderValue

                                                                                                                                        searchPlaceholderValue: string | null;
                                                                                                                                        • The value of the search inputs placeholder.

                                                                                                                                          **Input types affected:** select-one

                                                                                                                                          null

                                                                                                                                        property searchResultLimit

                                                                                                                                        searchResultLimit: number;
                                                                                                                                        • The maximum amount of search results to show. ("-1" indicates no limit)

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

                                                                                                                                          4

                                                                                                                                        property shadowRoot

                                                                                                                                        shadowRoot: ShadowRoot | null;
                                                                                                                                        • The shadow root for use within ShadowDom

                                                                                                                                        property shouldSort

                                                                                                                                        shouldSort: boolean;
                                                                                                                                        • Whether choices and groups should be sorted. If false, choices/groups will appear in the order they were given.

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

                                                                                                                                          true

                                                                                                                                        property shouldSortItems

                                                                                                                                        shouldSortItems: boolean;
                                                                                                                                        • Whether items should be sorted. If false, items will appear in the order they were selected.

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

                                                                                                                                          false

                                                                                                                                        property silent

                                                                                                                                        silent: boolean;
                                                                                                                                        • Optionally suppress console errors and warnings.

                                                                                                                                          **Input types affected:** text, select-single, select-multiple

                                                                                                                                          false

                                                                                                                                        property singleModeForMultiSelect

                                                                                                                                        singleModeForMultiSelect: boolean;
                                                                                                                                        • 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.

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

                                                                                                                                          false

                                                                                                                                        property sorter

                                                                                                                                        sorter: (current: Types.RecordToCompare, next: Types.RecordToCompare) => number;
                                                                                                                                        • 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.

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

                                                                                                                                          Example 1

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

                                                                                                                                          sortByAlpha

                                                                                                                                        property uniqueItemText

                                                                                                                                        uniqueItemText: string | Types.NoticeStringFunction;
                                                                                                                                        • If no duplicates are allowed, and the value already exists in the array.

                                                                                                                                          Return type must be safe to insert into HTML (ie use the 1st argument which is sanitised)

                                                                                                                                          'Only unique values can be added'

                                                                                                                                        property valueComparer

                                                                                                                                        valueComparer: Types.ValueCompareFunction;
                                                                                                                                        • Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a valueComparer argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example).

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

                                                                                                                                          (choice, item) => choice === item;

                                                                                                                                        interface State

                                                                                                                                        interface State {}

                                                                                                                                          property choices

                                                                                                                                          choices: ChoiceFull[];

                                                                                                                                            property groups

                                                                                                                                            groups: GroupFull[];

                                                                                                                                              property items

                                                                                                                                              items: ChoiceFull[];

                                                                                                                                                Type Aliases

                                                                                                                                                type ActionTypes

                                                                                                                                                type ActionTypes = Types.ValueOf<typeof ActionType>;

                                                                                                                                                  type EventChoiceValueType

                                                                                                                                                  type EventChoiceValueType<B extends boolean> = B extends true ? string : EventChoice;

                                                                                                                                                    type EventTypes

                                                                                                                                                    type EventTypes = Types.ValueOf<typeof EventType>;

                                                                                                                                                      type PassedElementType

                                                                                                                                                      type PassedElementType = Types.ValueOf<typeof PassedElementTypes>;

                                                                                                                                                        type PositionOptionsType

                                                                                                                                                        type PositionOptionsType = 'auto' | 'top' | 'bottom';

                                                                                                                                                          type StateChangeSet

                                                                                                                                                          type StateChangeSet = {
                                                                                                                                                          [K in keyof State]: boolean;
                                                                                                                                                          };

                                                                                                                                                            Namespaces

                                                                                                                                                            namespace Types

                                                                                                                                                            namespace Types {}

                                                                                                                                                              interface RecordToCompare

                                                                                                                                                              interface RecordToCompare {}

                                                                                                                                                                property label

                                                                                                                                                                label?: StringUntrusted | string;

                                                                                                                                                                  property value

                                                                                                                                                                  value?: StringUntrusted | string;

                                                                                                                                                                    type CustomProperties

                                                                                                                                                                    type CustomProperties = Record<string, any> | string;

                                                                                                                                                                      type EscapeForTemplateFn

                                                                                                                                                                      type EscapeForTemplateFn = (
                                                                                                                                                                      allowHTML: boolean,
                                                                                                                                                                      s: StringUntrusted | StringPreEscaped | string
                                                                                                                                                                      ) => string;

                                                                                                                                                                        type FilterFunction

                                                                                                                                                                        type FilterFunction = (value: string) => boolean;

                                                                                                                                                                          type GetClassNamesFn

                                                                                                                                                                          type GetClassNamesFn = (s: string | Array<string>) => string;

                                                                                                                                                                            type NoticeLimitFunction

                                                                                                                                                                            type NoticeLimitFunction = (maxItemCount: number) => string;

                                                                                                                                                                              type NoticeStringFunction

                                                                                                                                                                              type NoticeStringFunction = (value: string, valueRaw: string) => string;

                                                                                                                                                                                type StringFunction

                                                                                                                                                                                type StringFunction = () => string;

                                                                                                                                                                                  type StrToEl

                                                                                                                                                                                  type StrToEl = (str: string) => HTMLElement | HTMLInputElement | HTMLOptionElement;

                                                                                                                                                                                    type ValueCompareFunction

                                                                                                                                                                                    type ValueCompareFunction = (value1: string, value2: string) => boolean;

                                                                                                                                                                                      type ValueOf

                                                                                                                                                                                      type ValueOf<T extends object> = T[keyof T];

                                                                                                                                                                                        Package Files (19)

                                                                                                                                                                                        Dependencies (1)

                                                                                                                                                                                        Dev Dependencies (51)

                                                                                                                                                                                        Peer Dependencies (0)

                                                                                                                                                                                        No peer dependencies.

                                                                                                                                                                                        Badge

                                                                                                                                                                                        To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                                                                        You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/choices.js.

                                                                                                                                                                                        • Markdown
                                                                                                                                                                                          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/choices.js)
                                                                                                                                                                                        • HTML
                                                                                                                                                                                          <a href="https://www.jsdocs.io/package/choices.js"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>