Complete reference for the main Choices class and its core functionality including lifecycle management, basic operations, and instance control.
{ .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;
}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
});{ .api }
/**
* @param element - CSS selector string or DOM element
* @param userConfig - Configuration options (merged with defaults)
*/
constructor(element?: string | Element, userConfig?: Partial<Options>){ .api }
/**
* Initialize the Choices instance
* @returns {Choices} - Returns the instance for chaining
*/
init(): ChoicesUsage:
const choices = new Choices('#my-select');
choices.init(); // Explicitly initialize
// Or initialization happens automatically in constructor
const autoChoices = new Choices('#auto-select', { /* config */ });{ .api }
/**
* Destroy the Choices instance and clean up
* Restores original element and removes event listeners
* @returns {void}
*/
destroy(): voidUsage:
choices.destroy(); // Clean up everything
// Original select element is restored{ .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(): ChoicesUsage:
choices.disable(); // Make read-only
choices.enable(); // Re-enable interactions
// Chaining
choices.disable().setValue(['value1']).enable();{ .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}, ...]{ .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): ChoicesUsage:
// 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' });{ .api }
/**
* Select a choice by its value
* @param value - The value to select
* @returns {Choices} - Returns the instance for chaining
*/
setChoiceByValue(value: string): ChoicesUsage:
choices.setChoiceByValue('specific-value');
// Works with single and multi-select
multiSelect.setChoiceByValue('add-this-option');{ .api }
/**
* Clear the input field (search text)
* @returns {Choices} - Returns the instance for chaining
*/
clearInput(): Choices{ .api }
/**
* Clear all available choices from dropdown
* @returns {Choices} - Returns the instance for chaining
*/
clearChoices(): Choices{ .api }
/**
* Clear all data (choices and selected items)
* @returns {Choices} - Returns the instance for chaining
*/
clearStore(): ChoicesUsage:
choices.clearInput(); // Clear search text only
choices.clearChoices(); // Remove all dropdown options
choices.clearStore(); // Reset everything to empty state{ .api }
/**
* Show the dropdown list
* @param preventInputFocus - If true, prevents focusing the input
* @returns {Choices} - Returns the instance for chaining
*/
showDropdown(preventInputFocus?: boolean): Choices{ .api }
/**
* Hide the dropdown list
* @param preventInputBlur - If true, prevents blurring the input
* @returns {Choices} - Returns the instance for chaining
*/
hideDropdown(preventInputBlur?: boolean): ChoicesUsage:
// 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{ .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
};// Check if instance is ready
if (choices.initialised) {
choices.setValue(['new-value']);
}// Access current configuration
console.log(choices.config.searchEnabled);
console.log(choices.config.maxItemCount);
// Note: Modifying config after initialization may not take effect// 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');
});Most methods return the instance for convenient chaining:
choices
.clearStore()
.setValue(['option1'])
.showDropdown()
.disable();
// Conditional chaining
choices
.clearChoices()
[someCondition ? 'enable' : 'disable']()
.setValue(newValues);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"]');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');
}// 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.