or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdcore-usage.mddata-management.mdevents.mdindex.mdtemplates.mdtypes.md
tile.json

core-usage.mddocs/

Core Usage

Complete reference for the main Choices class and its core functionality including lifecycle management, basic operations, and instance control.

Main Choices Class

{ .api }
class Choices {
  constructor(element?: string | Element, userConfig?: Partial<Options>);
  
  // Static properties
  static get defaults(): { options: Options; templates: Templates };
  
  // Instance properties
  initialised: boolean;
  config: Options;
  passedElement: PassedElement;
  containerOuter: Container;
  containerInner: Container;
  choiceList: List;
  itemList: List;
  input: Input;
  dropdown: Dropdown;
}

Constructor

import Choices from 'choices.js';

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

// With element reference
const element = document.querySelector('#my-select');
const choices = new Choices(element);

// With configuration
const choices = new Choices('#my-select', {
  searchEnabled: true,
  removeItemButton: true,
  maxItemCount: 5
});

Constructor Parameters

{ .api }
/**
 * @param element - CSS selector string or DOM element
 * @param userConfig - Configuration options (merged with defaults)
 */
constructor(element?: string | Element, userConfig?: Partial<Options>)

Lifecycle Methods

Initialize Component

{ .api }
/**
 * Initialize the Choices instance
 * @returns {Choices} - Returns the instance for chaining
 */
init(): Choices

Usage:

const choices = new Choices('#my-select');
choices.init(); // Explicitly initialize

// Or initialization happens automatically in constructor
const autoChoices = new Choices('#auto-select', { /* config */ });

Destroy Component

{ .api }
/**
 * Destroy the Choices instance and clean up
 * Restores original element and removes event listeners
 * @returns {void}
 */
destroy(): void

Usage:

choices.destroy(); // Clean up everything
// Original select element is restored

Enable/Disable Component

{ .api }
/**
 * Enable the component (allow interactions)
 * @returns {Choices} - Returns the instance for chaining
 */
enable(): Choices

/**
 * Disable the component (prevent interactions)
 * @returns {Choices} - Returns the instance for chaining
 */
disable(): Choices

Usage:

choices.disable(); // Make read-only
choices.enable();  // Re-enable interactions

// Chaining
choices.disable().setValue(['value1']).enable();

Value Management Methods

Get Current Values

{ .api }
/**
 * Get the current value(s) of the instance
 * @param valueOnly - If true, returns only values; if false, returns full items
 * @returns {string | string[] | Item | Item[]} - Current values or items
 */
getValue(valueOnly?: boolean): string | string[] | Item | Item[]

Usage:

// Get just values (default behavior)
const values = choices.getValue(); // ['value1', 'value2']
const values = choices.getValue(true); // ['value1', 'value2']

// Get full item objects
const items = choices.getValue(false);
// [{id: 1, value: 'value1', label: 'Label 1', selected: true}, ...]

Set Values Programmatically

{ .api }
/**
 * Set the value(s) of the instance
 * @param items - Array of values/items or single value/item
 * @returns {Choices} - Returns the instance for chaining
 */
setValue(items: string[] | string | Item[] | Item): Choices

Usage:

// Set string values
choices.setValue(['option1', 'option2']);
choices.setValue('single-option');

// Set with item objects
choices.setValue([
  { value: 'opt1', label: 'Option 1' },
  { value: 'opt2', label: 'Option 2' }
]);

// Single item object
choices.setValue({ value: 'single', label: 'Single Option' });

Select Choice by Value

{ .api }
/**
 * Select a choice by its value
 * @param value - The value to select
 * @returns {Choices} - Returns the instance for chaining
 */
setChoiceByValue(value: string): Choices

Usage:

choices.setChoiceByValue('specific-value');

// Works with single and multi-select
multiSelect.setChoiceByValue('add-this-option');

Clear Methods

Clear Input Field

{ .api }
/**
 * Clear the input field (search text)
 * @returns {Choices} - Returns the instance for chaining
 */
clearInput(): Choices

Clear All Choices

{ .api }
/**
 * Clear all available choices from dropdown
 * @returns {Choices} - Returns the instance for chaining
 */
clearChoices(): Choices

Clear Entire Store

{ .api }
/**
 * Clear all data (choices and selected items)
 * @returns {Choices} - Returns the instance for chaining
 */
clearStore(): Choices

Usage:

choices.clearInput();   // Clear search text only
choices.clearChoices(); // Remove all dropdown options
choices.clearStore();   // Reset everything to empty state

Dropdown Control Methods

Show Dropdown

{ .api }
/**
 * Show the dropdown list
 * @param preventInputFocus - If true, prevents focusing the input
 * @returns {Choices} - Returns the instance for chaining
 */
showDropdown(preventInputFocus?: boolean): Choices

Hide Dropdown

{ .api }
/**
 * Hide the dropdown list
 * @param preventInputBlur - If true, prevents blurring the input
 * @returns {Choices} - Returns the instance for chaining
 */
hideDropdown(preventInputBlur?: boolean): Choices

Usage:

// Basic dropdown control
choices.showDropdown();
choices.hideDropdown();

// Advanced control
choices.showDropdown(true);  // Show but keep current focus
choices.hideDropdown(true);  // Hide but maintain input focus

Static Properties

Default Configuration Access

{ .api }
/**
 * Get default configuration and templates
 * @returns {{ options: Options, templates: Templates }}
 */
static get defaults(): { options: Options; templates: Templates }

Usage:

// Access defaults
const defaults = Choices.defaults;
console.log(defaults.options.searchEnabled); // true
console.log(defaults.templates.item); // Function

// Create custom config based on defaults
const customConfig = {
  ...Choices.defaults.options,
  searchEnabled: false,
  maxItemCount: 3
};

Instance Properties

Initialization State

// Check if instance is ready
if (choices.initialised) {
  choices.setValue(['new-value']);
}

Configuration Access

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

// Note: Modifying config after initialization may not take effect

Component Access

// Access internal components for advanced usage
const outerElement = choices.containerOuter.element;
const inputElement = choices.input.element;
const dropdownElement = choices.dropdown.element;

// Add custom event listeners
choices.input.element.addEventListener('focus', () => {
  console.log('Input focused');
});

Method Chaining

Most methods return the instance for convenient chaining:

choices
  .clearStore()
  .setValue(['option1'])
  .showDropdown()
  .disable();

// Conditional chaining
choices
  .clearChoices()
  [someCondition ? 'enable' : 'disable']()
  .setValue(newValues);

Element Types Support

Choices.js works with different input element types:

// Single select
const singleSelect = new Choices('select[data-single]');

// Multiple select  
const multiSelect = new Choices('select[multiple]');

// Text input
const textInput = new Choices('input[type="text"]');

Error Handling

try {
  const choices = new Choices('#nonexistent-element');
} catch (error) {
  console.error('Element not found:', error);
}

// Check initialization status
if (!choices.initialised) {
  console.warn('Choices not properly initialized');
}

Performance Considerations

// Efficient bulk operations
choices.clearStore();
choices.setChoices(largeChoicesArray, 'value', 'label', true);

// Avoid frequent updates in loops
const updates = ['val1', 'val2', 'val3'];
choices.setValue(updates); // Better than multiple setValue calls

// Clean up when done
window.addEventListener('beforeunload', () => {
  choices.destroy();
});

This covers all core functionality needed to effectively use the Choices class for basic and advanced scenarios.