### 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(
`
\ '
);
},
};
},
} );
```
--------------------------------
### 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 `