Choices.js

repository·main·Indexed 27 days ago

https://github.com/choices-js/choices

A lightweight, vanilla JavaScript plugin for creating configurable select boxes and text inputs. It serves as a jQuery-free alternative to libraries like Select2 and Selectize, supporting fast searching, custom templates, and flexible styling for text, select-one, and select-multiple HTML elements.

Tokens
21.8K
Snippets
34
Records
111
Agent score
90%

What's inside choices.js

  1. Set up a local development environment

    main

    To develop on Choices.js locally, follow these steps:

    1. Clone the repository.
    2. Navigate to the directory.
    3. Install dependencies: npm install

    Playwright (E2E Testing)

    End-to-end tests require Playwright. Install it using: npx playwright install npx playwright install-deps

    npm install
    npx playwright install
    npx playwright install-deps
  2. Listen to Choices events

    main

    Choices fires standard DOM events on the element passed to the constructor. You can access event data via the event.detail object. You can attach listeners either directly to the original element or via the passedElement.element property of the Choices instance.

    const element = document.getElementById('example');
    const example = new Choices(element);
    
    element.addEventListener('addItem', function(event) {
      console.log(event.detail.id);
      console.log(event.detail.value);
    }, false);
  3. Install Choices.js via CDN

    main

    To use Choices.js without a package manager, include the CSS and JavaScript files from a CDN. It is recommended to pin a specific version to ensure stability. You can include the optional base CSS for additional styling.

    <!-- Include base CSS (optional) -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/choices.js@11.1.0/public/assets/styles/base.min.css"
    />
    
    <!-- Include Choices CSS -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/choices.js@11.1.0/public/assets/styles/choices.min.css"
    />
    
    <!-- Include Choices JavaScript (versioned) -->
    <script src="https://cdn.jsdelivr.net/npm/choices.js@11.1.0/public/assets/scripts/choices.min.js"></script>
  4. Call Choices.js methods directly or via chaining

    main

    Methods in Choices.js can be invoked by chaining them directly onto the constructor or by calling them on the instance returned by the constructor.

    // Chaining methods
    const choices = new Choices(element, {
      addItems: false,
      removeItems: false,
    }).setValue(['Set value 1', 'Set value 2']).disable();
    
    // Calling methods directly
    const choices = new Choices(element, {
      addItems: false,
      removeItems: false,
    });
    choices.setValue(['Set value 1', 'Set value 2']);
    choices.disable();
    // Calling a method by chaining
    const choices = new Choices(element, {
      addItems: false,
      removeItems: false,
    })
      .setValue(['Set value 1', 'Set value 2'])
      .disable();
    
    // Calling a method directly
    const choices = new Choices(element, {
      addItems: false,
      removeItems: false,
    });
    
    choices.setValue(['Set value 1', 'Set value 2']);
    choices.disable();
  5. Initialize Choices.js

    main

    To initialize the plugin, create a new instance of Choices by passing an HTML element or a CSS selector. If a selector matches multiple elements, only the first one will be used.

    // Pass single element
    const element = document.querySelector('.js-choice');
    const choices = new Choices(element);
    
    // Pass reference (selector string)
    const choices = new Choices('[data-trigger]');
    const choices = new Choices('.js-choice');
    
    // Pass jQuery element
    const choices = new Choices($('.js-choice')[0]);
  6. Customize choice sorting with sorter

    main

    The sorter option allows you to define a custom function to sort choices and items before they are displayed. By default, Choices.js uses sortByAlpha. If shouldSort is set to false, choices/groups will appear in the order they were provided.

    // 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;
      },
    });
  7. Filter added items with addItemFilter

    main

    The addItemFilter option allows you to restrict what users can add to a text input. You can provide a string (treated as a RegExp), a RegExp object, or a function that returns true for valid items.

    // Only adds items matching the text test
    new Choices(element, {
      addItemFilter: (value) => {
        return ['orange', 'apple', 'banana'].includes(value);
      };
    });
    
    // only items ending to `-red`
    new Choices(element, {
      addItemFilter: '-red$';
    });
  8. Configure choices for select inputs

    main

    Use the choices option to add options to select-one or select-multiple inputs. You can pass an array of objects representing individual choices or groups of choices.

    Each choice object can include value, label, selected, disabled, and customProperties.

    [
      {
        value: 'Option 1',
        label: 'Option 1',
        selected: true,
        disabled: false,
      },
      {
        label: 'Group 1',
        choices: [{
          value: 'Option 3',
          label: 'Option 4',
          selected: true,
          disabled: false,
        }]
      }
    ]
  9. Customize Choices.js with CSS custom properties

    main

    Since version 11.2, you can customize the appearance and behavior of Choices.js using CSS custom properties. This allows for easy theming of colors, spacing, font sizes, and more without overriding complex CSS selectors.

    To implement a dark mode, you can wrap these properties in a @media (prefers-color-scheme: dark) block.

    @media (prefers-color-scheme: dark) {
      :root {
        --choices-primary-color: #38daff;
        --choices-item-color: black;
        --choices-bg-color: #101010;
        --choices-bg-color-dropdown: #101010;
        --choices-keyline-color: #3b3e40;
        --choices-bg-color-disabled: #181a1b;
        --choices-item-disabled-color: #eee;
        --choices-disabled-color: #2d2d2d;
        --choices-highlighted-color: #16292d;
        --choices-icon-cross: url("data:image/svg+xml;base64,...");
        --choices-icon-cross-inverse: url("data:image/svg+xml;base64,...");
      }
    }