or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdcore-class.mdevents.mdindex.mdtemplates.md
tile.json

core-class.mddocs/

Core Choices Class

The main Choices class provides the primary API for initializing and controlling enhanced select and input elements. It serves as the single entry point for all functionality and manages the complete lifecycle of choice-enabled elements.

Capabilities

Constructor

Creates a new Choices instance on the specified element with optional configuration.

/**
 * Creates a new Choices instance
 * @param element - CSS selector string, DOM element, or HTML input/select element
 * @param userConfig - Optional configuration object to customize behavior
 */
constructor(
  element?: string | Element | HTMLInputElement | HTMLSelectElement,
  userConfig?: Partial<Options>
);

Usage Examples:

import Choices from "choices.js";

// Basic initialization with CSS selector
const choices1 = new Choices('.js-choice');

// Direct element reference  
const element = document.getElementById('my-select');
const choices2 = new Choices(element);

// With configuration
const choices3 = new Choices('#text-input', {
  delimiter: ',',
  editItems: true,
  maxItemCount: 10,
  removeItemButton: true,
  placeholder: true,
  placeholderValue: 'Type to add items...'
});

Static Properties

Access to version information and default configuration.

/**
 * Version number of the Choices library
 */
static version: string;

/**
 * Default configuration and templates
 */
static defaults: {
  options: Partial<Options>;
  allOptions: Options;
  templates: Templates;
};

Usage Examples:

// Check version
console.log(Choices.version);

// Access default configuration
const defaultConfig = Choices.defaults.allOptions;

// Get default templates
const defaultTemplates = Choices.defaults.templates;

// Modify global defaults
Choices.defaults.options.searchEnabled = false;

Lifecycle Methods

Methods for managing the instance lifecycle including initialization and cleanup.

/**
 * Initialize the Choices instance and set up DOM manipulation
 */
init(): void;

/**
 * Destroy the instance and clean up DOM modifications and event listeners
 */
destroy(): void;

/**
 * Enable the input/select element and restore interactivity
 */
enable(): this;

/**
 * Disable the input/select element and prevent user interaction
 */
disable(): this;

Usage Examples:

const choices = new Choices('#my-select');

// Manual initialization (usually automatic)
choices.init();

// Disable temporarily
choices.disable();

// Re-enable
choices.enable();

// Clean up when done
choices.destroy();

Value Management

Methods for programmatically setting and managing the selected values.

/**
 * Get the current selected values
 * @param valueOnly - Whether to return just values (true) or full EventChoice objects (false)
 * @returns Single value/object for select-one, array for select-multiple
 */
getValue<B extends boolean = false>(valueOnly?: B): EventChoiceValueType<B> | EventChoiceValueType<B>[];

/**
 * Set the values of the input programmatically
 * @param items - Array of strings or InputChoice objects to set as values
 */
setValue(items: string[] | InputChoice[]): this;

/**
 * Set choice selection by value for select elements
 * @param value - Single value string or array of values to select
 */
setChoiceByValue(value: string | string[]): this;

/**
 * Set choices dynamically for select elements
 * @param choicesArrayOrFetcher - Array of choices/groups or async function returning choices
 * @param value - Property name to use as value (default: 'value')
 * @param label - Property name to use as label (default: 'label')
 * @param replaceChoices - Whether to replace existing choices (default: false)
 * @param clearSearchFlag - Whether to clear search state (default: true)
 */
setChoices(
  choicesArrayOrFetcher: 
    | (InputChoice | InputGroup)[]
    | ((instance: Choices) => (InputChoice | InputGroup)[] | Promise<(InputChoice | InputGroup)[]>),
  value?: string | null,
  label?: string,
  replaceChoices?: boolean,
  clearSearchFlag?: boolean
): this | Promise<this>;

/**
 * Refresh/re-render the choices with optional behavior controls
 * @param withEvents - Whether to trigger events during refresh
 * @param selectFirstOption - Whether to select the first available option
 * @param deselectAll - Whether to clear all current selections
 */
refresh(
  withEvents?: boolean, 
  selectFirstOption?: boolean, 
  deselectAll?: boolean
): this;

Usage Examples:

// Get current selected values
const selectedValues = choices.getValue(true); // Returns just values
const selectedObjects = choices.getValue(false); // Returns EventChoice objects

// Set text input values
choices.setValue(['apple', 'banana', 'cherry']);

// Set with InputChoice objects
choices.setValue([
  { value: 'red', label: 'Red Color', selected: true },
  { value: 'blue', label: 'Blue Color' }
]);

// Select specific choices by value
choices.setChoiceByValue('option1');
choices.setChoiceByValue(['option1', 'option2']);

// Set choices dynamically
choices.setChoices([
  { value: 'option1', label: 'Option One' },
  { value: 'option2', label: 'Option Two', disabled: true }
], 'value', 'label', true); // Replace existing choices

// Set choices with async function
choices.setChoices(async () => {
  const response = await fetch('/api/choices');
  return response.json();
});

// Set grouped choices
choices.setChoices([
  {
    label: 'Fruits',
    choices: [
      { value: 'apple', label: 'Apple' },
      { value: 'banana', label: 'Banana' }
    ]
  },
  {
    label: 'Vegetables', 
    choices: [
      { value: 'carrot', label: 'Carrot' },
      { value: 'broccoli', label: 'Broccoli' }
    ]
  }
]);

// Refresh the display
choices.refresh();
choices.refresh(true, false, true); // with events, don't select first, deselect all

Item Management

Methods for managing individual items/selections within the choices interface.

/**
 * Highlight a specific item
 * @param item - The InputChoice item to highlight
 * @param runEvent - Whether to trigger highlight events
 */
highlightItem(item: InputChoice, runEvent?: boolean): this;

/**
 * Remove highlight from a specific item
 * @param item - The InputChoice item to unhighlight  
 * @param runEvent - Whether to trigger unhighlight events
 */
unhighlightItem(item: InputChoice, runEvent?: boolean): this;

/**
 * Highlight all currently selected items
 */
highlightAll(): this;

/**
 * Remove highlighting from all items
 */
unhighlightAll(): this;

/**
 * Remove all items that match the specified value
 * @param value - The value to match for removal
 */
removeActiveItemsByValue(value: string): this;

/**
 * Remove all active items except optionally one with excluded ID
 * @param excludedId - Optional ID to exclude from removal
 */
removeActiveItems(excludedId?: number): this;

/**
 * Remove all currently highlighted items
 * @param runEvent - Whether to trigger removal events
 */
removeHighlightedItems(runEvent?: boolean): this;

Dropdown Control

Methods for programmatically controlling the dropdown visibility.

/**
 * Show the dropdown list
 * @param preventInputFocus - Whether to prevent focusing the input when showing
 */
showDropdown(preventInputFocus?: boolean): this;

/**
 * Hide the dropdown list
 * @param preventInputBlur - Whether to prevent blurring the input when hiding
 */
hideDropdown(preventInputBlur?: boolean): this;

Choice Management

Methods for managing the available choices in select elements.

/**
 * Remove a choice by its value
 * @param value - The value of the choice to remove
 */
removeChoice(value: string): this;

/**
 * Clear all available choices from select elements
 */
clearChoices(): this;

/**
 * Clear the internal store/state
 * @param clearOptions - Whether to also clear the original select options
 */
clearStore(clearOptions?: boolean): this;

/**
 * Clear the current input value
 */
clearInput(): this;

Instance Properties

Key properties available on Choices instances for state inspection.

/**
 * Whether the instance has been initialized
 */
readonly initialised: boolean;

/**
 * Whether initialization completed successfully
 */
readonly initialisedOK?: boolean;

/**
 * The merged configuration options for this instance
 */
readonly config: Options;

Usage Examples:

const choices = new Choices('#my-select');

// Check initialization status
if (choices.initialised) {
  console.log('Choices is ready');
}

// Access configuration
console.log(choices.config.maxItemCount);

// Check if initialization was successful  
if (choices.initialisedOK) {
  console.log('Choices initialized without errors');
}