### Install Project Dependencies Source: https://github.com/choices-js/choices/blob/main/README.md Run this command after cloning the repository to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Run Development Server Source: https://github.com/choices-js/choices/blob/main/CONTRIBUTING.md Starts a local server for active development and testing. ```bash npm run start ``` -------------------------------- ### Get Value - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Demonstrates retrieving full choice objects and retrieving only the value strings using `getValue(true)`. ```javascript // Get full objects const values = choices.getValue(); // Returns: [{id: 1, value: 'apple', label: 'Apple'}, ...] // Get only values const valueStrings = choices.getValue(true); // Returns: ['apple', 'banana', ...] ``` -------------------------------- ### Install Choices.js via npm Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Use npm to install the Choices.js library. This is the standard method for including the library in your project. ```bash npm install choices.js ``` -------------------------------- ### Initialize Choices with Options Source: https://github.com/choices-js/choices/blob/main/_autodocs/configuration.md Basic example of initializing Choices with a configuration object. All options are optional and have sensible defaults. ```typescript const choices = new Choices(element, { // Configuration options }); ``` -------------------------------- ### Set Value - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Shows how to set values using an array of strings and an array of objects with 'value' and 'label' properties. ```javascript // Set with string array choices.setValue(['apple', 'banana']); // Set with objects choices.setValue([ { value: 'apple', label: 'Apple' }, { value: 'banana', label: 'Banana' } ]); ``` -------------------------------- ### Install Choices.js with Yarn Source: https://github.com/choices-js/choices/blob/main/README.md Use this command to add Choices.js to your project via Yarn. ```zsh yarn add choices.js ``` -------------------------------- ### Browser Polyfill Example Source: https://github.com/choices-js/choices/blob/main/README.md Example of a polyfill script used for browser compatibility, including specific features. ```html ``` -------------------------------- ### Install Playwright Source: https://github.com/choices-js/choices/blob/main/README.md Installs Playwright, a tool for end-to-end testing. OS support may also be required. ```bash npx playwright install ``` ```bash npx playwright install-deps ``` -------------------------------- ### Show Dropdown - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Shows the dropdown list, with an option to prevent the input from gaining focus. ```javascript choices.showDropdown(); choices.showDropdown(true); // Show but don't focus the input ``` -------------------------------- ### Remove Highlighted Items - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Demonstrates how to highlight all items and then remove them using `removeHighlightedItems(true)`. ```javascript choices.highlightAll(); choices.removeHighlightedItems(true); // Removes all items ``` -------------------------------- ### Configure Choices.js Options Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Initialize Choices.js with a configuration object to customize various aspects of its behavior and appearance. This example shows options for search, item management, display, styling, and callbacks. ```javascript new Choices(element, { // Search searchEnabled: true, searchFields: ['label', 'value'], searchFloor: 1, // Items addItems: true, maxItemCount: 5, removeItems: true, // Display placeholderValue: 'Choose an option', allowHTML: false, // Styling classNames: { /* ... */ }, // Callbacks callbackOnInit: function() { /* ... */ } }); ``` -------------------------------- ### Basic Text Input Setup with Choices.js Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md Use this for text inputs where users can add multiple tags or keywords. Configure maximum item count and placeholder text. Items can be added programmatically or via user input. ```javascript import Choices from 'choices.js'; // HTML // const element = document.getElementById('tags'); const choices = new Choices(element, { addItems: true, removeItems: true, maxItemCount: 5, placeholderValue: 'Add tags (max 5)' }); // Programmatically add items choices.setValue(['javascript', 'react']); // Get current values const tags = choices.getValue(true); console.log(tags); // ['javascript', 'react'] ``` -------------------------------- ### Method Chaining Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-index.md Demonstrates how most Choices.js instance methods return `this` to enable method chaining for sequential operations. ```javascript const choices = new Choices(element) .setValue(['apple', 'banana']) .highlightAll() .disable(); ``` -------------------------------- ### Basic Select Multiple with Performance Options Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index-performance.html Initializes a select multiple input with 2000 options, demonstrating the setup for performance testing. Uses allowHTML and shouldSort: false for potential performance gains. ```javascript document.addEventListener('DOMContentLoaded', function() { const options = [...new Array(2000)].map((_, index) => ({ selected: !!(index % 2), label: `Choice ${index + 1}$`, value: `Choice ${index + 1}$`, })); const choices = new Choices('#choices-basic', { allowHTML: true, shouldSort: false, choices: options, }); document.querySelector('button.disable').addEventListener('click', () => { choices.disable(); }); document.querySelector('button.enable').addEventListener('click', () => { choices.enable(); }); document.querySelector('button.setChoices').addEventListener('click', () => { const options = [...new Array(20000)].map((_, index) => ({ selected: !!(index % 2), label: `Choice ${index + 1}$`, value: `Choice ${index + 1}$`, })); choices.setChoices(options, null, null, true); }); }); ``` -------------------------------- ### EventChoice Usage Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/types.md Demonstrates how to listen for the 'addItem' event and access the EventChoice object from the event details to log choice information. ```javascript choices.passedElement.element.addEventListener('addItem', (event) => { const choice: EventChoice = event.detail; console.log(choice.value, choice.label, choice.groupValue); }); ``` -------------------------------- ### TypeScript Definitions and Usage Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Demonstrates how to import and use TypeScript definitions for Choices.js configuration and item creation. Ensure you have the 'choices.js' package installed. ```typescript import Choices, { Options, InputChoice, EventChoice } from 'choices.js'; const config: Options = { /* ... */ }; const choices: Choices = new Choices(element, config); const choice: InputChoice = { value: 'x', label: 'X' }; ``` -------------------------------- ### Set Choice by Value - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Demonstrates selecting a single choice by its value and selecting multiple choices using an array of values. ```javascript const choices = new Choices(selectElement, { choices: [ { value: 'apple', label: 'Apple' }, { value: 'banana', label: 'Banana' } ] }); choices.setChoiceByValue('apple'); // Selects apple choices.setChoiceByValue(['apple', 'banana']); // Selects both ``` -------------------------------- ### Input Width While Typing Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index.html Demonstrates how the input width adjusts dynamically as the user types. This example focuses on the default behavior without specific configuration for width adjustment. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-input-width-typing', {}); }); ``` -------------------------------- ### Disabled Choice Example Source: https://github.com/choices-js/choices/blob/main/public/test/select-one/index.html Initializes Choices.js with options allowing HTML and item removal, demonstrating a scenario where one choice might be disabled. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-disabled-choice', { allowHTML: true, removeItemButton: true, }); }); ``` -------------------------------- ### Event Listener Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/constants-and-utilities.md Demonstrates how to use the EventType constants or string literals to add event listeners for item additions. This allows for custom actions when items are added to the Choices instance. ```javascript import Choices, { EventType } from 'choices.js'; const choices = new Choices(element); // Using the constant choices.passedElement.element.addEventListener(EventType.addItem, (e) => { console.log('Item added:', e.detail.value); }); // Or use string directly choices.passedElement.element.addEventListener('addItem', (e) => { console.log('Item added:', e.detail.value); }); ``` -------------------------------- ### Run Unit Tests in Watch Mode Source: https://github.com/choices-js/choices/blob/main/CONTRIBUTING.md Starts a test server that automatically re-runs unit tests upon file changes. ```bash npm run test:unit:watch ``` -------------------------------- ### PassedElementTypes Usage Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/constants-and-utilities.md Shows how to instantiate Choices with different element types and how to check the internal _elementType property against the PassedElementTypes constants. ```javascript import Choices, { PassedElementTypes } from 'choices.js'; const textChoices = new Choices(document.querySelector('input[type="text"]')); // textChoices._elementType === PassedElementTypes.Text const selectChoices = new Choices(document.querySelector('select')); // selectChoices._elementType === PassedElementTypes.SelectOne ``` -------------------------------- ### Placeholder Configuration in Choices.js Source: https://github.com/choices-js/choices/blob/main/README.md Configure placeholder behavior for text inputs. This example shows how to enable a placeholder and use a data attribute for its value. ```html ``` -------------------------------- ### Customizing Class Names in Choices.js Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/constants-and-utilities.md Example demonstrating how to override default CSS class names when initializing Choices.js. This allows for custom styling of elements. ```javascript new Choices(element, { classNames: { containerOuter: ['my-select-wrapper'], item: ['tag', 'tag-default'], itemDisabled: ['tag', 'tag-disabled'], selectedState: ['selected', 'is-chosen'] } }); ``` -------------------------------- ### Choices.js Custom Properties Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/types.md Demonstrates how to attach arbitrary key-value data to choices using the `customProperties` object. This data can be used for filtering or display purposes and can be searched by including paths to these properties in `searchFields`. ```javascript const choice = { value: 'apple', label: 'Apple', customProperties: { color: 'red', season: 'fall', nutrition: { calories: 95, fiber: 4.4 } } }; // Search these fields by including in searchFields choices.config.searchFields = ['label', 'customProperties.color', 'customProperties.nutrition.calories']; ``` -------------------------------- ### Choices Class Initialization and Basic Usage Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Demonstrates how to import and initialize the Choices.js class with basic configuration options, and how to set and retrieve values. It also shows how to listen for change events. ```APIDOC ## Choices Class Initialization and Basic Usage ### Description This section demonstrates the fundamental usage of the Choices.js library, including importing the class, initializing it with an HTML element and configuration options, setting values, retrieving values, and listening for change events. ### Method JavaScript ### Code ```javascript import Choices from 'choices.js'; // Initialize with an element and configuration options const choices = new Choices(element, { searchEnabled: true, removeItems: true }); // Set values for the choices instance choices.setValue(['apple', 'banana']); // Get the current values from the choices instance const values = choices.getValue(true); // Returns an array of values, e.g., ['apple', 'banana'] // Listen for the 'change' event on the element element.addEventListener('change', (e) => { console.log('Changed:', e.detail.value); }); ``` ### Parameters - **element**: The HTML element to initialize Choices.js on. - **options** (object) - Optional: Configuration options for Choices.js. - **searchEnabled** (boolean) - Optional: Enables or disables the search functionality. Defaults to `false`. - **removeItems** (boolean) - Optional: Enables or disables the ability to remove items. Defaults to `false`. ### Response - **choices**: An instance of the Choices.js class. - **values**: An array of the current selected values. ``` -------------------------------- ### Create Custom Item and Choice Templates in Choices.js Source: https://github.com/choices-js/choices/blob/main/README.md This example demonstrates a more complex use of callbackOnCreateTemplates to define custom HTML for item and choice elements, including adding a star icon and handling data attributes. Ensure data attributes defined here are maintained for Choices to function correctly. ```javascript // StrToEl = (str: string) => HTMLElement | HTMLInputElement | HTMLOptionElement; // EscapeForTemplateFn = (allowHTML: boolean, s: StringUntrusted | StringPreEscaped | string) => string; // GetClassNamesFn = (s: string | Array) => string; const example = new Choices(element, { callbackOnCreateTemplates: function(strToEl /*:StrToEl*/, escapeForTemplate /*:EscapeForTemplateFn*/, getClassNames /*:GetClassNamesFn*/) { return { item: ({ classNames }, data) => { return strToEl( `
${escapeForTemplate(true, data.label)}
` ); }, choice: ({ classNames }, data) => { return strToEl( `
0 ? 'role="treeitem"' : 'role="option"' }> ${escapeForTemplate(true, data.label)}
` ); }, }; }, }); ``` -------------------------------- ### Initialize Choices with Preset Options and Groups Source: https://github.com/choices-js/choices/blob/main/public/index.html Shows how to initialize Choices.js with predefined options organized into groups. This is useful for structured lists of choices. ```javascript var singlePresetOpts = new Choices('#choices-single-preset-options', { allowHTML: true, placeholder: true, }).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' }, ], }, ], 'value', 'label' ); ``` -------------------------------- ### Get Input Values Source: https://github.com/choices-js/choices/blob/main/README.md Retrieve the current values from the input. Pass `true` to `getValue` to get only the values as strings. Otherwise, it returns an array of choice objects. ```javascript const example = new Choices(element); const values = example.getValue(true); // returns ['value 1', 'value 2']; const valueArray = example.getValue(); // returns [{ active: true, choiceId: 1, highlighted: false, id: 1, label: 'Label 1', value: 'Value 1'}, { active: true, choiceId: 2, highlighted: false, id: 2, label: 'Label 2', value: 'Value 2'}]; ``` -------------------------------- ### Get Current Values Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-index.md Retrieve the currently selected values from the Choices.js instance. ```APIDOC ## Get Current Values ### Description Retrieve the currently selected values from the Choices.js instance. ### Method `getValue()` ### Returns An array of the selected item values. ``` -------------------------------- ### Initialize Choices with Custom Options Source: https://github.com/choices-js/choices/blob/main/public/index.html Demonstrates initializing Choices.js with options like `allowHTML`, `addItems`, and `removeItems`. Use this for basic configuration of input fields. ```javascript var textDisabled = new Choices('#choices-text-disabled', { allowHTML: true, addItems: false, removeItems: false, }).disable(); ``` ```javascript var textPrependAppendVal = new Choices( '#choices-text-prepend-append-value', { allowHTML: true, prependValue: 'item-', appendValue: '-' + Date.now(), } ).removeActiveItems(); ``` ```javascript var textPresetVal = new Choices('#choices-text-preset-values', { allowHTML: true, items: [ 'Josh Johnson', { value: 'joe@bloggs.com', label: 'Joe Bloggs', customProperties: { description: 'Joe Blogg is such a generic name', }, }, ], }); ``` -------------------------------- ### Hide Dropdown - Example Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Hides the dropdown list, with an option to keep the input focused. ```javascript choices.hideDropdown(); choices.hideDropdown(true); // Hide but keep input focused ``` -------------------------------- ### Initialize Choices.js with Options Source: https://github.com/choices-js/choices/blob/main/README.md Shows how to initialize Choices.js with a custom set of options. This includes configuration for silent mode, item limits, search behavior, and custom class names. Refer to the Choices.js documentation for a full list of available options. ```javascript // Passing options (with default options) const choices = new Choices(element, { silent: false, items: [], choices: [], renderChoiceLimit: -1, maxItemCount: -1, closeDropdownOnSelect: 'auto', singleModeForMultiSelect: false, addChoices: false, addItems: true, addItemFilter: (value) => !!value && value !== '', removeItems: true, removeItemButton: false, removeItemButtonAlignLeft: false, editItems: false, allowHTML: false, allowHtmlUserInput: false, duplicateItemsAllowed: true, delimiter: ',', paste: true, searchEnabled: true, searchChoices: true, searchDisabledChoices: false, searchFloor: 1, searchResultLimit: 4, searchFields: ['label', 'value'], position: 'auto', resetScrollPosition: true, shouldSort: true, shouldSortItems: false, sorter: (a, b) => sortByAlpha, shadowRoot: null, placeholder: true, placeholderValue: null, searchPlaceholderValue: null, prependValue: null, appendValue: null, renderSelectedChoices: 'auto', searchRenderSelectedChoices: true, loadingText: 'Loading...', noResultsText: 'No results found', noChoicesText: 'No choices to choose from', itemSelectText: 'Press to select', uniqueItemText: 'Only unique values can be added', customAddItemText: 'Only values matching specific conditions can be added', addItemText: (value, rawValue) => { return `Press Enter to add "${value}"`; }, removeItemIconText: () => `Remove item`, removeItemLabelText: (value, rawValue) => `Remove item: ${value}`, maxItemText: (maxItemCount) => { return `Only ${maxItemCount} values can be added`; }, valueComparer: (value1, value2) => { return value1 === value2; }, classNames: { containerOuter: ['choices'], containerInner: ['choices__inner'], input: ['choices__input'], inputCloned: ['choices__input--cloned'], list: ['choices__list'], listItems: ['choices__list--multiple'], listSingle: ['choices__list--single'], listDropdown: ['choices__list--dropdown'], item: ['choices__item'], itemSelectable: ['choices__item--selectable'], itemDisabled: ['choices__item--disabled'], itemChoice: ['choices__item--choice'], description: ['choices__description'], placeholder: ['choices__placeholder'], group: ['choices__group'], groupHeading: ['choices__heading'], button: ['choices__button'], activeState: ['is-active'], focusState: ['is-focused'], openState: ['is-open'], disabledState: ['is-disabled'], highlightedState: ['is-highlighted'], selectedState: ['is-selected'], flippedState: ['is-flipped'], loadingState: ['is-loading'], invalidState: ['is-invalid'], notice: ['choices__notice'], addChoice: ['choices__item--selectable', 'add-choice'], noResults: ['has-no-results'], noChoices: ['has-no-choices'], }, // Choices uses the great Fuse library for searching. You // can find more options here: https://fusejs.io/api/options.html fuseOptions: { includeScore: true }, labelId: '', callbackOnInit: null, callbackOnCreateTemplates: null, appendGroupInSearch: false, }); ``` -------------------------------- ### getValue Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Gets the current value(s) of the input. Can return full choice objects or just the value strings. ```APIDOC ## getValue() ### Description Gets the current value(s) of the input. You can choose to retrieve either the full choice objects or just the value strings. ### Method `getValue(valueOnly?: B): EventChoiceValueType | EventChoiceValueType[]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **valueOnly** (boolean) - Optional - Default: `false` - If true, returns only the value strings. If false, returns full choice objects. ### Request Example ```javascript // Get full objects const values = choices.getValue(); // Returns: [{id: 1, value: 'apple', label: 'Apple'}, ...] // Get only values const valueStrings = choices.getValue(true); // Returns: ['apple', 'banana', ...] ``` ### Response #### Success Response - **EventChoiceValueType | EventChoiceValueType[]** - For select-one: single value. For text/select-multiple: array. When `valueOnly` is true, returns string(s); otherwise returns EventChoice object(s). #### Response Example ```javascript // Example response for valueOnly = false: // [{id: 1, value: 'apple', label: 'Apple'}] // Example response for valueOnly = true: // ['apple'] ``` ``` -------------------------------- ### Initialize Choices with Groups and Fetch Data Source: https://github.com/choices-js/choices/blob/main/public/index.html Shows how to initialize Choices.js with grouped options and how to populate choices dynamically using `fetch` API. Useful for large datasets or remote data sources. ```javascript var multipleDefault = new Choices( document.getElementById('choices-multiple-groups'), { allowHTML: true } ); ``` ```javascript var multipleFetch = new Choices('#choices-multiple-remote-fetch', { allowHTML: false, placeholder: true, placeholderValue: 'Pick an Strokes record', maxItemCount: 5, }).setChoices(function() { return fetch( 'https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW' ) .then(function(response) { return response.json(); }) .then(function(data) { return data.releases.map(function(release) { return { value: release.title, label: release.title }; }); }); }); ``` -------------------------------- ### Initialize Choices.js with Options Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Demonstrates how to initialize Choices.js with search and item removal enabled. This snippet also shows how to set initial values, retrieve current values, and listen for change events. ```javascript import Choices from 'choices.js'; // Initialize const choices = new Choices(element, { searchEnabled: true, removeItems: true }); // Set values choices.setValue(['apple', 'banana']); // Get values const values = choices.getValue(true); // ['apple', 'banana'] // Listen to events element.addEventListener('change', (e) => { console.log('Changed:', e.detail.value); }); ``` -------------------------------- ### Get Value - TypeScript Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-reference/choices-class.md Retrieves the current value(s) of the input. Can return full choice objects or just the value strings. ```typescript getValue(valueOnly?: B): EventChoiceValueType | EventChoiceValueType[] ``` -------------------------------- ### Listen to addItem Event Source: https://github.com/choices-js/choices/blob/main/README.md Example of how to listen for the 'addItem' event on a Choices.js element. This event fires when an item is added to the choices list. ```javascript const element = document.getElementById('example'); const example = new Choices(element); element.addEventListener( 'addItem', function(event) { // do something creative here... console.log(event.detail.id); console.log(event.detail.value); console.log(event.detail.label); console.log(event.detail.customProperties); console.log(event.detail.groupValue); }, false, ); // or const example = new Choices(document.getElementById('example')); example.passedElement.element.addEventListener( 'addItem', function(event) { // do something creative here... console.log(event.detail.id); console.log(event.detail.value); console.log(event.detail.label); console.log(event.detail.customProperties); console.log(event.detail.groupValue); }, false, ); ``` -------------------------------- ### Initialize Choices.js with Custom Properties and HTML Labels Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index.html Enable HTML rendering for labels and configure search fields to include custom properties. `allowHTML` is set to true. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-custom-properties-html', { allowHTML: true, searchFields: ['label', 'value', 'customProperties'], }); }); ``` -------------------------------- ### Build Lightweight Bundle (No Fuse.js) Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md Build Choices.js with basic prefix search only, disabling the default fuzzy matching provided by Fuse.js. This reduces bundle size for simpler search needs. ```bash # Build with basic prefix search only (no fuzzy matching) CHOICES_SEARCH_FUSE=null npm run build ``` -------------------------------- ### Build Lightweight Bundle (KMP Algorithm) Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md Build Choices.js using the KMP substring algorithm for search, offering an alternative to Fuse.js. This option provides efficient substring searching. ```bash # Or with KMP substring algorithm CHOICES_SEARCH_FUSE=null CHOICES_SEARCH_KMP=1 npm run build ``` -------------------------------- ### Build CSS Source: https://github.com/choices-js/choices/blob/main/CONTRIBUTING.md Compiles, minifies, and prefixes SCSS files into standard CSS. ```bash npm run css:build ``` -------------------------------- ### Initialize Choices.js with Custom Templates Source: https://github.com/choices-js/choices/blob/main/public/index.html Demonstrates initializing Choices.js with custom item and choice templates. This allows for rich HTML rendering within the select dropdown and selected items. ```javascript var customTemplates = new Choices(document.getElementById('choices-single-custom-templates'), { allowHTML: true, position: 'bottom', callbackOnCreateTemplates: function(strToEl, escapeForTemplate) { var classNames = this.config.classNames; var itemSelectText = this.config.itemSelectText; var allowHTML = this.config.allowHTML; return { item: function({ classNames }, data) { return strToEl( '\ \ 🎉 ' + String(escapeForTemplate(allowHTML, data.label)) + '\ \ ' ); }, choice: function({ classNames }, data) { return strToEl( '\ 0 ? 'role="treeitem"' : 'role="option"' ) + '\ >\ 👉🏽 ' + String(escapeForTemplate(allowHTML, data.label)) + '\ \ ' ); }, }; }, } ); ``` -------------------------------- ### Main Methods Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Provides a list of core methods available on a Choices instance for managing its state and behavior. ```APIDOC ## Main Methods ### `init()` Initialize the instance (called automatically) ### `destroy()` Remove Choices UI and restore original element ### `enable()` / `disable()` Control interactivity ### `setValue()` / `getValue()` Get/set items ### `setChoices()` / `setChoiceByValue()` Set choices (select elements) ### `clearChoices()` / `clearStore()` Remove choices or all data ### `showDropdown()` / `hideDropdown()` Control dropdown visibility ### `highlightItem()` / `unhighlightItem()` Highlight items ### `removeChoice()` / `removeActiveItems()` Remove items All methods are chainable (return `this`). ### Example ```javascript choices .setValue(['apple', 'banana']) .disable(); ``` ``` -------------------------------- ### Custom Value Comparer Function Source: https://github.com/choices-js/choices/blob/main/README.md Use a custom compare function for `setChoiceByValue` to define how values are matched. This example trims whitespace before comparison. ```javascript const example = new Choices(element, { valueComparer: (a, b) => value.trim() === b.trim(), }); ``` -------------------------------- ### Initialize Choices with Custom Properties and Set Choice by Value Source: https://github.com/choices-js/choices/blob/main/public/index.html Demonstrates initializing Choices.js with custom properties for search fields and pre-selecting an option. Use custom properties to enable searching by additional data associated with each choice. ```javascript var singleSelectedOpt = new Choices('#choices-single-selected-option', { allowHTML: true, searchFields: ['label', 'value', 'customProperties.description'], choices: [ { value: 'One', label: 'Label One', selected: true }, { value: 'Two', label: 'Label Two', disabled: true }, { value: 'Three', label: 'Label Three', customProperties: { description: 'This option is fantastic', }, }, ], }).setChoiceByValue('Two'); ``` ```javascript var customChoicesPropertiesViaDataAttributes = new Choices( '#choices-with-custom-props-via-html', { allowHTML: true, searchFields: ['label', 'value', 'customProperties'], } ); ``` -------------------------------- ### Multi-Select with Groups using Choices.js Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md Configure multi-select dropdowns with grouped options for better organization. This setup is suitable for ` const element = document.getElementById('cities'); const choices = new Choices(element, { searchEnabled: true, removeItems: true, placeholder: true }); // Set choices with groups choices.setChoices([ { label: 'North America', choices: [ { value: 'nyc', label: 'New York City' }, { value: 'la', label: 'Los Angeles' }, { value: 'tor', label: 'Toronto' } ] }, { label: 'Europe', choices: [ { value: 'lon', label: 'London' }, { value: 'par', label: 'Paris' }, { value: 'ber', label: 'Berlin' } ] } ]); // Get selected values const selected = choices.getValue(true); console.log(selected); // ['nyc', 'par'] ``` -------------------------------- ### Custom Sorter Function for Choices.js Source: https://github.com/choices-js/choices/blob/main/README.md Use a custom function to define the sorting logic for choices and items. This example sorts by the length of the label from largest to smallest. ```javascript const example = new Choices(element, { sorter: function(a, b) { return b.label.length - a.label.length; }, }); ``` -------------------------------- ### Initialize Choices.js with HTML Allowed and Add Choices Enabled Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index.html Enable HTML rendering in choices and allow new choices to be added by the user. `addChoices` is set to true. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-allowhtml-true', { allowHTML: true, allowHtmlUserInput: true, addChoices: true, choices: [ { id: 1, label: 'Choice 1', value: 'Choice 1', selected: true }, { id: 2, label: 'Choice 2', value: 'Choice 2', }, { id: 3, label: 'Choice 3', value: 'Choice 3', }, ], }); }); ``` -------------------------------- ### Customize Input Template with Choices.js Source: https://github.com/choices-js/choices/blob/main/README.md Use callbackOnCreateTemplates to extend the default input template, for example, to set the input type to 'email'. The `this` keyword refers to the Choices instance. ```javascript const example = new Choices(element, { callbackOnCreateTemplates: (strToEl, escapeForTemplate, getClassNames) => ({ input: (...args) => Object.assign(Choices.defaults.templates.input.call(this, ...args), { type: 'email', }), }), }); ``` -------------------------------- ### Custom Item Addition Filter with String Suffix Source: https://github.com/choices-js/choices/blob/main/README.md Use a string as an addItemFilter to only allow items that end with a specific suffix. This example only allows items ending with '-red'. ```javascript // only items ending to `-red` new Choices(element, { addItemFilter: '-red$'; }); ``` -------------------------------- ### Google Analytics Tracking Source: https://github.com/choices-js/choices/blob/main/public/index.html This snippet attempts to set up Google Analytics tracking. It includes a fallback for environments where 'ga' might not be defined and logs any errors encountered during setup. ```javascript try { window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments); }; ga.l = +new Date(); ga('create', 'UA-31575166-1', 'auto'); ga('send', 'pageview'); } catch (e) { console.log(e); } ``` -------------------------------- ### Chained and Direct Method Calls in Choices.js Source: https://github.com/choices-js/choices/blob/main/README.md Demonstrates how to call methods on a Choices.js instance, both by chaining multiple method calls and by calling them directly on the instance. Ensure the element is correctly selected before initializing Choices.js. ```javascript const choices = new Choices(element, { addItems: false, removeItems: false, }) .setValue(['Set value 1', 'Set value 2']) .disable(); ``` ```javascript const choices = new Choices(element, { addItems: false, removeItems: false, }); choices.setValue(['Set value 1', 'Set value 2']); choices.disable(); ``` -------------------------------- ### Custom Item Addition Filter Function Source: https://github.com/choices-js/choices/blob/main/README.md Use a custom function to filter user input before adding items. This example only allows items that are present in a predefined list of fruits. ```javascript // Only adds items matching the text test new Choices(element, { addItemFilter: (value) => { return ['orange', 'apple', 'banana'].includes(value); }; }); ``` -------------------------------- ### Configuration Options Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Details on how to customize Choices.js behavior using the configuration object during initialization. ```APIDOC ## Configuration Pass an options object to customize behavior: ```javascript new Choices(element, { // Search searchEnabled: true, searchFields: ['label', 'value'], searchFloor: 1, // Items addItems: true, maxItemCount: 5, removeItems: true, // Display placeholderValue: 'Choose an option', allowHTML: false, // Styling classNames: { /* ... */ }, // Callbacks callbackOnInit: function() { /* ... */ } }); ``` See [configuration.md](configuration.md) for all 50+ options. ``` -------------------------------- ### Handling Optional Parameters Source: https://github.com/choices-js/choices/blob/main/_autodocs/api-index.md Explains that optional parameters in Choices.js methods can be omitted, in which case their default values are used. This example shows a method call with and without an optional boolean parameter. ```javascript choices.setValue(['a', 'b']); // Uses defaults choices.highlightItem(item, true); // Trigger event choices.highlightItem(item); // Same as true (default) ``` -------------------------------- ### Initialize Choices.js with Reset Functionality Source: https://github.com/choices-js/choices/blob/main/public/index.html Demonstrates initializing Choices.js with options for resetting selections. This includes a simple reset and a reset for multiple select inputs with item removal buttons. ```javascript var resetSimple = new Choices(document.getElementById('reset-simple'), { allowHTML: true }); var resetMultiple = new Choices('#reset-multiple', { allowHTML: true, removeItemButton: true, }); ``` -------------------------------- ### init() Source: https://github.com/choices-js/choices/blob/main/README.md Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM. This is called implicitly when a new instance of Choices is created. This would be used after a Choices instance had already been destroyed (using `destroy()`). ```APIDOC ## init() ### Description Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM. This is called implicitly when a new instance of Choices is created. This would be used after a Choices instance had already been destroyed (using `destroy()`). ### Method `init()` ### Parameters None ### Request Example ```javascript const choices = new Choices(element); choices.init(); ``` ### Response None ``` -------------------------------- ### Vue Component for Choices.js Integration Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md A Vue 3 component that integrates Choices.js, managing its lifecycle and handling events. It uses `ref` for DOM access and `onMounted`/`onBeforeUnmount` for setup and cleanup. ```javascript import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'; import Choices from 'choices.js'; export default defineComponent({ name: 'ChoicesSelect', props: { options: Array, modelValue: [String, Array] }, emits: ['update:modelValue'], setup(props, { emit }) { const selectRef = ref(null); const choicesInstance = ref(null); onMounted(() => { choicesInstance.value = new Choices(selectRef.value, { searchEnabled: true }); if (props.options) { choicesInstance.value.setChoices(props.options, 'value', 'label', true); } selectRef.value.addEventListener('change', () => { const value = choicesInstance.value.getValue(true); emit('update:modelValue', value); }); }); onBeforeUnmount(() => { choicesInstance.value?.destroy(); }); return { selectRef }; }, template: '' }); ``` -------------------------------- ### Initialize Choices.js with Choice Groups Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index.html Organize choices into groups using the `optgroup` HTML element. `allowHTML` is enabled. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-groups', { allowHTML: true, }); }); ``` -------------------------------- ### Enable/Disable Choices.js based on Selection Source: https://github.com/choices-js/choices/blob/main/public/index.html This example shows how to dynamically enable or disable a Choices.js instance based on the value selected in another Choices.js instance. It uses an event listener on the 'change' event. ```javascript var cities = new Choices(document.getElementById('cities'), { allowHTML: true }); var tubeStations = new Choices( document.getElementById('tube-stations'), { allowHTML: true } ).disable(); cities.passedElement.element.addEventListener('change', function(e) { if (e.detail.value === 'London') { tubeStations.enable(); } else { tubeStations.disable(); } }); ``` -------------------------------- ### Build JavaScript Source: https://github.com/choices-js/choices/blob/main/CONTRIBUTING.md Compiles Choices.js into an uglified JavaScript file for production. ```bash npm run js:build ``` -------------------------------- ### Listen to Choices.js Events Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Attach event listeners to the underlying HTML element to react to user interactions with Choices.js. This example shows how to capture 'addItem' and 'change' events, logging details about the added or changed values. ```javascript element.addEventListener('addItem', (event) => { console.log('Added:', event.detail.value); }); element.addEventListener('change', (event) => { console.log('Changed:', event.detail.value); }); ``` -------------------------------- ### Initialize Choices with XHR Fetch and No Search Source: https://github.com/choices-js/choices/blob/main/public/index.html Demonstrates initializing Choices.js with remote data fetched via XHR and disabling the search functionality. Use this when the list of options is short or search is not desired. ```javascript var singleXhrRemove = new Choices('#choices-single-remove-xhr', { allowHTML: true, removeItemButton: true, searchPlaceholderValue: "Search for a Smiths' record", }).setChoices(function(callback) { return fetch( 'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW' ) .then(function(res) { return res.json(); }) .then(function(data) { return data.releases.map(function(release) { return { label: release.title, value: release.title }; }); }); }); ``` ```javascript var singleNoSearch = new Choices('#choices-single-no-search', { allowHTML: true, searchEnabled: false, removeItemButton: true, choices: [ { value: 'One', label: 'Label One' }, { value: 'Two', label: 'Label Two', disabled: true }, { value: 'Three', label: 'Label Three' }, ], }).setChoices( [ { value: 'Four', label: 'Label Four', disabled: true }, { value: 'Five', label: 'Label Five' }, { value: 'Six', label: 'Label Six', selected: true }, ], 'value', 'label', false ); ``` -------------------------------- ### Initialize Choices.js with Various Selectors Source: https://github.com/choices-js/choices/blob/main/README.md Demonstrates how to initialize Choices.js by passing a single element, a CSS selector, or a jQuery element. Note that if a selector targets multiple elements, only the first one will be used. ```javascript // Pass single element const element = document.querySelector('.js-choice'); const choices = new Choices(element); ``` ```javascript // Pass reference const choices = new Choices('[data-trigger]'); const choices = new Choices('.js-choice'); ``` ```javascript // Pass jQuery element const choices = new Choices($('.js-choice')[0]); ``` -------------------------------- ### Autocomplete with Custom Search Logic Source: https://github.com/choices-js/choices/blob/main/public/test/select-one/index.html Implements an autocomplete feature where choices are dynamically filtered based on user input. This example clears choices if the query is too short and sets new choices based on a specific prefix. ```javascript document.addEventListener('DOMContentLoaded', function() { const choices = new Choices('#choices-autocomplete', { shouldSort: false, renderSelectedChoices: false, }); choices.passedElement.element.addEventListener( 'search', function(e) { const query = e.detail.value; if (query.length < 2) { choices.clearChoices(); return; } let result = []; if (query.slice(0, 2) === 'fo') { result = [{ value: 'found', label: 'Found' }]; } choices.setChoices(result, 'value', 'label', true); } ); }); ``` -------------------------------- ### Pre-populate Text Input with Items Source: https://github.com/choices-js/choices/blob/main/_autodocs/configuration.md Initialize a text input with a predefined list of items. Items can be provided as a simple array of strings or an array of objects with `value` and `label` properties. ```javascript // String array new Choices(element, { items: ['apple', 'banana', 'orange'] }); ``` ```javascript // Object array new Choices(element, { items: [ { value: 'apple', label: 'Apple' }, { value: 'banana', label: 'Banana' } ] }); ``` -------------------------------- ### Constructor Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Initializes a new Choices instance on a specified HTML element with optional configuration. ```APIDOC ## Constructor Creates a Choices instance on a text input or select element. ### Parameters - `element` (string | Element) - CSS selector or element reference - `config` (Partial) - Configuration object ### Example ```javascript const c1 = new Choices('.my-select'); const c2 = new Choices(document.getElementById('tags'), { addItems: true }); ``` ``` -------------------------------- ### Form Validation with Choices.js Source: https://github.com/choices-js/choices/blob/main/_autodocs/examples.md Implement form submission validation by retrieving selected values from a Choices.js instance and applying custom rules. This example checks if at least one email is selected and if the count does not exceed a limit before submitting the form. ```javascript import Choices from 'choices.js'; const choices = new Choices('#email-select'); const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); const emails = choices.getValue(true); if (emails.length === 0) { alert('Please select at least one email'); return; } if (emails.length > 5) { alert('You can only select up to 5 emails'); return; } // Valid! Submit form form.submit(); }); ``` -------------------------------- ### Import Choices.js with Different Search Backends Source: https://github.com/choices-js/choices/blob/main/_autodocs/README.md Import the Choices.js library with various search backend configurations. Choose the appropriate import based on your search requirements, from full fuzzy search to no search functionality. ```javascript import Choices from 'choices.js'; ``` ```javascript import Choices from 'choices.js/search-basic'; ``` ```javascript import Choices from 'choices.js/search-kmp'; ``` ```javascript import Choices from 'choices.js/search-none'; ``` -------------------------------- ### Initialize Choices.js with Placeholder via Option Attribute Source: https://github.com/choices-js/choices/blob/main/public/test/select-multiple/index.html Configure a placeholder using a data attribute on the option element. `allowHTML` should be enabled for HTML content. ```javascript document.addEventListener('DOMContentLoaded', function() { new Choices('#choices-placeholder-via-option-attr', { allowHTML: true, }); }); ```