### HTML Structure for Programmatic Examples
Source: https://select2.org/programmatic-control/methods
The markup required for the programmatic control demonstration.
```html
```
--------------------------------
### Initialize Select2 with AJAX
Source: https://select2.org/data-sources/ajax
Basic setup for a Select2 control using a remote data source.
```html
```
```javascript
$('.js-example-data-ajax').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json'
// Additional AJAX parameters go here; see the end of this page for the full code of this example
}
});
```
--------------------------------
### JavaScript Logic for Programmatic Examples
Source: https://select2.org/programmatic-control/methods
Event handlers for controlling the Select2 instances defined in the HTML.
```javascript
var $example = $(".js-example-programmatic").select2();
var $exampleMulti = $(".js-example-programmatic-multi").select2();
$(".js-programmatic-set-val").on("click", function() {
$example.val("CA").trigger("change");
});
$(".js-programmatic-open").on("click", function() {
$example.select2("open");
});
$(".js-programmatic-close").on("click", function() {
$example.select2("close");
});
$(".js-programmatic-init").on("click", function() {
$example.select2();
});
$(".js-programmatic-destroy").on("click", function() {
$example.select2("destroy");
});
$(".js-programmatic-multi-set-val").on("click", function() {
$exampleMulti.val(["CA", "AL"]).trigger("change");
});
$(".js-programmatic-multi-clear").on("click", function() {
$exampleMulti.val(null).trigger("change");
});
```
--------------------------------
### Data with selected and disabled options
Source: https://select2.org/data-sources/formats
Example showing how to define pre-selected and disabled options within the data structure.
```json
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2",
"selected": true
},
{
"id": 3,
"text": "Option 3",
"disabled": true
}
]
}
```
--------------------------------
### Include Bower-installed Select2 files
Source: https://select2.org/getting-started/installation
Reference the local paths for Select2 files after running bower install.
```html
```
--------------------------------
### Example selection data object
Source: https://select2.org/programmatic-control/events
The structure of the data object returned by e.params.data.
```json
{
"id": 1,
"text": "Tyto alba",
"genus": "Tyto",
"species": "alba"
}
```
--------------------------------
### HTML Select Element with Placeholder Option
Source: https://select2.org/upgrading/migrating-from-35
Example of a select element where the first option serves as the placeholder.
```html
```
--------------------------------
### Matching grouped options
Source: https://select2.org/searching?q=
Implements a custom matcher for nested data structures by iterating through children. This example filters results based on whether the term appears at the start of the string.
```javascript
function matchStart(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Skip if there is no 'children' property
if (typeof data.children === 'undefined') {
return null;
}
// `data.children` contains the actual options that we are matching against
var filteredChildren = [];
$.each(data.children, function(idx, child) {
if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
filteredChildren.push(child);
}
});
// If we matched any of the timezone group's children, then set the matched children on the group
// and return the group object
if (filteredChildren.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.children = filteredChildren;
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-matcher-start").select2({
matcher: matchStart
});
```
--------------------------------
### HTML OptGroup Structure
Source: https://select2.org/options?q=
Example of standard HTML optgroup usage that Select2 automatically parses.
```html
```
--------------------------------
### Loading initial options via AJAX
Source: https://select2.org/upgrading/migrating-from-35?q=
Alternative approach for loading initial options by manually creating and appending option tags to the select element.
```javascript
var $element = $('select').select2(); // the select element you are working with
var $request = $.ajax({
url: '/my/remote/source' // wherever your data is actually coming from
});
$request.then(function(data) {
// This assumes that the data comes back as an array of data objects
// The idea is that you are using the same callback as the old `initSelection`
for (var d = 0; d < data.length; d++) {
var item = data[d];
// Create the DOM option that is pre-selected by default
var option = new Option(item.text, item.id, true, true);
// Append it to the select
$element.append(option);
}
// Update the selected options that are displayed
$element.trigger('change');
});
```
--------------------------------
### Configure multi-select placeholder
Source: https://select2.org/placeholders?q=
Do not include an empty option element for multi-select configurations.
```html
```
```javascript
$(".js-example-placeholder-multiple").select2({
placeholder: "Select a state"
});
```
--------------------------------
### Initialize Select2 with nested ajax options
Source: https://select2.org/configuration/data-attributes?q=
Standard JavaScript initialization for nested ajax configuration.
```javascript
$(".js-example-data-ajax").select2({
ajax: {
url: "http://example.org/api/test",
cache: false
}
});
```
--------------------------------
### Include manually downloaded Select2 files
Source: https://select2.org/getting-started/installation
Reference the local paths for Select2 files after manual download and placement.
```html
```
--------------------------------
### Initialize Select2 with Width Resolution
Source: https://select2.org/appearance
Apply the width configuration to the responsive select elements to override default behavior.
```javascript
$(".js-example-responsive").select2({
width: 'resolve' // need to override the changed default
});
```
--------------------------------
### Select2 Configuration Options
Source: https://select2.org/configuration/options-api?q=
A comprehensive list of configuration options for customizing Select2 instances.
```APIDOC
## Select2 Configuration Options
### Description
These options are used to configure the behavior and appearance of a Select2 component during initialization.
### Options
- **ajax** (object) - Provides support for ajax data sources.
- **allowClear** (boolean) - Provides support for clearable selections.
- **amdLanguageBase** (string) - Base path for AMD/CommonJS language files.
- **closeOnSelect** (boolean) - Controls whether the dropdown is closed after a selection is made.
- **data** (array of objects) - Allows rendering dropdown options from an array.
- **dataAdapter** (object) - Used to override the built-in DataAdapter.
- **debug** (boolean) - Enable debugging messages in the browser console.
- **dir** (string) - Sets the dir attribute (ltr/rtl).
- **disabled** (boolean) - When set to true, the select control will be disabled.
- **dropdownAdapter** (object) - Used to override the built-in DropdownAdapter.
- **dropdownAutoWidth** (boolean) - Sets the width on the dropdown dynamically whenever it is opened.
- **dropdownCssClass** (string) - Adds additional CSS classes to the dropdown container.
- **dropdownParent** (jQuery selector or DOM node) - Allows you to customize placement of the dropdown.
- **escapeMarkup** (callback) - Handles automatic escaping of content rendered by custom templates.
- **language** (string or object) - Specify the language used for Select2 messages.
- **matcher** (callback) - Handles custom search matching.
- **maximumInputLength** (integer) - Maximum number of characters for a search term.
- **maximumSelectionLength** (integer) - Maximum number of items that may be selected.
- **minimumInputLength** (integer) - Minimum number of characters required to start a search.
- **minimumResultsForSearch** (integer) - Minimum number of results required to display the search box.
- **multiple** (boolean) - Enables multi-select (pillbox) mode.
- **placeholder** (string or object) - Specifies the placeholder for the control.
- **resultsAdapter** (object) - Used to override the built-in ResultsAdapter.
- **selectionAdapter** (object) - Used to override the built-in SelectionAdapter.
- **selectionCssClass** (string) - Adds additional CSS classes to the selection container.
- **selectOnClose** (boolean) - Implements automatic selection when the dropdown is closed.
- **sorter** (callback) - Handles custom sorting of matched results.
- **tags** (boolean / array of objects) - Used to enable free text responses.
- **templateResult** (callback) - Customizes the way that search results are rendered.
- **templateSelection** (callback) - Customizes the way that selections are rendered.
- **theme** (string) - Allows you to set the theme.
- **tokenizer** (callback) - Handles automatic tokenization of free-text entry.
- **tokenSeparators** (array) - List of characters used as token separators.
- **width** (string) - Supports customization of the container width.
- **scrollAfterSelect** (boolean) - Controls scrolling behavior for multiselects.
```
--------------------------------
### Configure nested options with data attributes
Source: https://select2.org/configuration/data-attributes?q=
Using double dashes to define nested configuration options via data attributes.
```html
```
--------------------------------
### Create option if not exists
Source: https://select2.org/programmatic-control/add-select-clear-items
Check for an existing option using .find before creating and appending a new one.
```javascript
// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
$('#mySelect2').val(data.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data.text, data.id, true, true);
// Append it to the select
$('#mySelect2').append(newOption).trigger('change');
}
```
--------------------------------
### Initialize Select2 with RTL support
Source: https://select2.org/i18n
Configures Select2 to support right-to-left text direction.
```javascript
$(".js-example-rtl").select2({
dir: "rtl"
});
```
--------------------------------
### Configuring Placeholder with Object
Source: https://select2.org/upgrading/migrating-from-35
Using the placeholder option with an object to specify the ID of the placeholder option.
```javascript
$("select").select2({
placeholder: {
id: "-1",
placeholder: "Select an option"
}
});
```
--------------------------------
### Implement the base Adapter interface
Source: https://select2.org/advanced/adapters-and-decorators?q=
Defines the core methods required for all custom Select2 adapters to handle rendering, event binding, positioning, and destruction.
```javascript
// The basic HTML that should be rendered by Select2. A jQuery or DOM element
// should be returned, which will automatically be placed by Select2 within the
// DOM.
//
// @returns A jQuery or DOM element that contains any elements that must be
// rendered by Select2.
Adapter.render = function() {
return $jq;
};
// Bind to any Select2 or DOM events.
//
// @param container The Select2 object that is bound to the jQuery element. You
// can listen to Select2 events with `on` and trigger Select2 events using the
// `trigger` method.
// @param $container The jQuery DOM node that all default adapters will be
// rendered within.
Adapter.bind = function(container, $container) {};
// Position the DOM element within the Select2 DOM container, or in another
// place. This allows adapters to be located outside of the Select2 DOM,
// such as at the end of the document or in a specific place within the Select2
// DOM node.
//
// Note: This method is not called on data adapters.
//
// @param $rendered The rendered DOM element that was returned from the call to
// `render`. This may have been modified by Select2, but the root element
// will always be the same.
// @param $defaultContainer The default container that Select2 will typically
// place the rendered DOM element within. For most adapters, this is the
// Select2 DOM element.
Adapter.position = function($rendered, $defaultContainer) {};
// Destroy any events or DOM elements that have been created.
// This is called when `select2("destroy")` is called on an element.
Adapter.destroy = function() {};
```
--------------------------------
### open
Source: https://select2.org/programmatic-control/methods
The open method causes the Select2 dropdown menu to open and display selectable options.
```APIDOC
## .select2('open')
### Description
Causes the dropdown menu to open, displaying the selectable options.
### Usage
$('#mySelect2').select2('open');
```
--------------------------------
### Implement AJAX data loading with Select2
Source: https://select2.org/data-sources/ajax
Configures a Select2 instance to query the GitHub API with custom result and selection templates. Requires jQuery and the Select2 library.
```javascript
$(".js-example-data-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
placeholder: 'Search for a repository',
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
if (repo.loading) {
return repo.text;
}
var $container = $(
"
" +
"
" +
"
" +
"" +
"" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
"
);
$container.find(".select2-result-repository__title").text(repo.full_name);
$container.find(".select2-result-repository__description").text(repo.description);
$container.find(".select2-result-repository__forks").append(repo.forks_count + " Forks");
$container.find(".select2-result-repository__stargazers").append(repo.stargazers_count + " Stars");
$container.find(".select2-result-repository__watchers").append(repo.watchers_count + " Watchers");
return $container;
}
function formatRepoSelection(repo) {
return repo.full_name || repo.text;
}
```
--------------------------------
### Initialize Single Select Box
Source: https://select2.org/getting-started/basic-usage
HTML structure for a standard select element and the corresponding jQuery initialization.
```html
```
```javascript
// In your Javascript (external .js resource or
```
--------------------------------
### Select2 AJAX Configuration
Source: https://select2.org/data-sources/ajax?q=
Configuring a Select2 instance to fetch data from a remote URL using the ajax option.
```APIDOC
## Select2 AJAX Configuration
### Description
Configures the Select2 component to perform remote data lookups via AJAX. The ajax object passes parameters directly to jQuery's $.ajax function.
### Parameters
- **ajax.url** (string) - Required - The URL to which the request is sent.
- **ajax.dataType** (string) - Optional - The type of data expected back from the server.
- **ajax.data** (function) - Optional - A callback function to modify the query parameters sent to the server.
### Request Parameters (Default)
- **term** (string) - The current search term in the search box.
- **q** (string) - Contains the same contents as term.
- **_type** (string) - The request type (e.g., 'query' or 'query_append').
- **page** (number) - The current page number for paginated requests.
```
--------------------------------
### Using the legacy matcher compatibility wrapper
Source: https://select2.org/upgrading/migrating-from-35?q=
Wraps an old-style matcher function for use with the new Select2 API. This requires the full version of Select2 and the select2/compat/matcher module.
```javascript
function matchStart(term, text) {
if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
return true;
}
return false;
}
$.fn.select2.amd.require(['select2/compat/matcher'], function(oldMatcher) {
$(".js-example-matcher-compat").select2({
matcher: oldMatcher(matchStart)
})
});
```
--------------------------------
### Configure single select placeholder
Source: https://select2.org/placeholders?q=
Requires an empty first option in the HTML select element to function correctly.
```html
```
```javascript
$(".js-example-placeholder-single").select2({
placeholder: "Select a state",
allowClear: true
});
```
--------------------------------
### Initialize Select2 with Disabled Options
Source: https://select2.org/options?q=
Initialization and HTML structure for handling disabled options in Select2.
```javascript
var $disabledResults = $(".js-example-disabled-results");
$disabledResults.select2();
```
```html
```
--------------------------------
### Select2 AJAX Configuration Options
Source: https://select2.org/data-sources/ajax?q=
Configuration options for the Select2 AJAX module, including delay, URL generation, data mapping, result processing, and custom transport.
```APIDOC
## Select2 AJAX Configuration
### Description
Configure how Select2 fetches data from remote sources using the `ajax` object within the Select2 initialization.
### Configuration Options
- **delay** (number) - Optional - The number of milliseconds to wait for the user to stop typing before issuing the AJAX request.
- **url** (function) - Optional - A callback function that receives `params` and returns the URL string for the request.
- **data** (function) - Optional - A callback function that receives `params` and returns the data object to be sent with the request.
- **processResults** (function) - Optional - A callback function that receives the server response `data` and returns an object containing a `results` array.
- **transport** (function) - Optional - A custom function to handle the request, receiving `params`, `success`, and `failure` callbacks.
```
--------------------------------
### Enable Tagging in Select2
Source: https://select2.org/tagging
Initialize Select2 with the tags option set to true to allow dynamic option creation.
```javascript
$(".js-example-tags").select2({
tags: true
});
```
--------------------------------
### Configure amdLanguageBase
Source: https://select2.org/getting-started/builds-and-modules
Sets the base AMD loader language path for resolving language files when module names are modified during build steps.
```javascript
$.fn.select2.defaults.set('amdLanguageBase', 'select2/i18n/');
```
--------------------------------
### Configure camelCase options with data attributes
Source: https://select2.org/configuration/data-attributes?q=
Mapping camelCase options to dash-separated data attributes.
```html
```
```javascript
$("select").select2({
tags: "true",
placeholder: "Select an option",
allowClear: true
});
```
--------------------------------
### Implement custom data adapter
Source: https://select2.org/upgrading/migrating-from-35?q=
The modern approach to handling data retrieval in Select2 4.0 using AMD modules and data adapters.
```javascript
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function(ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function(params, callback) {
var data = {
results: []
};
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
$("#select").select2({
dataAdapter: CustomData
});
}
```
--------------------------------
### Retrieve selection data using the data method
Source: https://select2.org/programmatic-control/retrieving-selections?q=
Returns a JavaScript array of objects representing the current selection.
```javascript
$('#mySelect2').select2('data');
```
--------------------------------
### Use data object for placeholder
Source: https://select2.org/placeholders?q=
Provides a default selection object where the id matches the option value.
```javascript
$('select').select2({
placeholder: {
id: '-1', // the value of the option
text: 'Select an option'
}
});
```
--------------------------------
### Configure custom jQuery AJAX options
Source: https://select2.org/data-sources/ajax
Pass custom logic for URL generation, data formatting, result processing, and transport handling directly into the ajax configuration object.
```javascript
ajax: {
// The number of milliseconds to wait for the user to stop typing before
// issuing the ajax request.
delay: 250,
// You can craft a custom url based on the parameters that are passed into the
// request. This is useful if you are using a framework which has
// JavaScript-based functions for generating the urls to make requests to.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns The url that the request should be made to.
url: function(params) {
return UrlGenerator.Random();
},
// You can pass custom data into the request based on the parameters used to
// make the request. For `GET` requests, the default method, these are the
// query parameters that are appended to the url. For `POST` requests, this
// is the form data that will be passed into the request. For other requests,
// the data returned from here should be customized based on what jQuery and
// your server are expecting.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns Data to be directly passed into the request.
data: function(params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
// You can modify the results that are returned from the server, allowing you
// to make last-minute changes to the data, or find the correct part of the
// response to pass to Select2. Keep in mind that results should be passed as
// an array of objects.
//
// @param data The data as it is returned directly by jQuery.
// @returns An object containing the results data as well as any required
// metadata that is used by plugins. The object should contain an array of
// data objects as the `results` key.
processResults: function(data) {
return {
results: data
};
},
// You can use a custom AJAX transport function if you do not want to use the
// default one provided by jQuery.
//
// @param params The object containing the parameters used to generate the
// request.
// @param success A callback function that takes `data`, the results from the
// request.
// @param failure A callback function that indicates that the request could
// not be completed.
// @returns An object that has an `abort` function that can be called to abort
// the request if needed.
transport: function(params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
```
--------------------------------
### Implementing pagination parameters
Source: https://select2.org/data-sources/ajax
Override the ajax.data setting to include page parameters in the request sent to the server.
```javascript
$('#mySelect2').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: function(params) {
var query = {
search: params.term,
page: params.page || 1
}
// Query parameters will be ?search=[term]&page=[page]
return query;
}
}
});
```
--------------------------------
### Configure Bower dependency
Source: https://select2.org/getting-started/installation
Add this entry to your bower.json file to manage Select2 as a project dependency.
```json
"dependencies": {
"select2": "~4.1"
}
```
--------------------------------
### Apply a decorator to a Select2 adapter
Source: https://select2.org/advanced/adapters-and-decorators?q=
Use the Utils.Decorate method within an AMD require block to combine a base selection adapter with a decorator.
```javascript
$.fn.select2.amd.require(
["select2/utils", "select2/selection/single", "select2/selection/placeholder"],
function(Utils, SingleSelection, Placeholder) {
var CustomSelectionAdapter = Utils.Decorate(SingleSelection, Placeholder);
}
);
```
--------------------------------
### Reset global default options
Source: https://select2.org/configuration/defaults?q=
Restores all global default options to their initial state.
```javascript
$.fn.select2.defaults.reset();
```
--------------------------------
### Listening for Select2 Events
Source: https://select2.org/programmatic-control/events?q=
How to attach event listeners to a Select2 instance using jQuery's .on() method.
```APIDOC
## Listening for events
### Description
Attach event listeners to the `