### 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 ` ... ``` ```javascript $(document).ready(function() { $('.js-example-basic-multiple').select2(); }); ``` -------------------------------- ### Initialize Select2 with default diacritics support Source: https://select2.org/i18n Enables the default matcher that transliterates diacritic-modified letters to ASCII. ```javascript $(".js-example-diacritics").select2(); ``` -------------------------------- ### Apply Classic Theme to Select2 Source: https://select2.org/appearance Use the theme option to apply the classic styling to single and multiple select elements. ```javascript $(".js-example-theme-single").select2({ theme: "classic" }); $(".js-example-theme-multiple").select2({ theme: "classic" }); ``` -------------------------------- ### Custom data adapter with current method Source: https://select2.org/upgrading/migrating-from-35?q= Implementation of a custom data adapter using the current method to handle initial and updated selections in Select2 4.0. ```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.current = function(callback) { var data = []; var currentVal = this.$element.val(); if (!this.$element.prop('multiple')) { currentVal = [currentVal]; } for (var v = 0; v < currentVal.length; v++) { data.push({ id: currentVal[v], text: currentVal[v] }); } callback(data); }; $("#select").select2({ dataAdapter: CustomData }); }); ``` -------------------------------- ### Implement the DataAdapter interface Source: https://select2.org/advanced/adapters-and-decorators?q= Required methods for overriding default data retrieval and querying logic in Select2. ```javascript // Get the currently selected options. This is called when trying to get the // initial selection for Select2, as well as when Select2 needs to determine // what options within the results are selected. // // @param callback A function that should be called when the current selection // has been retrieved. The first parameter to the function should be an array // of data objects. DataAdapter.current = function(callback) { callback(currentData); } // Get a set of options that are filtered based on the parameters that have // been passed on in. // // @param params An object containing any number of parameters that the query // could be affected by. Only the core parameters will be documented. // @param params.term A user-supplied term. This is typically the value of the // search box, if one exists, but can also be an empty string or null value. // @param params.page The specific page that should be loaded. This is typically // provided when working with remote data sets, which rely on pagination to // determine what objects should be displayed. // @param callback The function that should be called with the queried results. DataAdapter.query = function(params, callback) { callback(queryiedData); } ``` -------------------------------- ### Open Select2 Dropdown Source: https://select2.org/programmatic-control/methods Invokes the open method to display the dropdown menu. ```javascript $('#mySelect2').select2('open'); ``` -------------------------------- ### Configure Select2 with data-placeholder Source: https://select2.org/configuration/data-attributes?q= Basic usage of data-placeholder attribute on a select element. ```html ``` -------------------------------- ### Initialize Select2 with local array data Source: https://select2.org/data-sources/arrays Uses a JavaScript array of objects to populate dropdown options. The data is rendered immediately into the select element. ```javascript var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }]; $(".js-example-data-array").select2({ data: data }) $(".js-example-data-array-selected").select2({ data: data }) ``` -------------------------------- ### Grouped data format Source: https://select2.org/data-sources/formats Structure for generating optgroups by nesting options under a 'children' key. ```json { "results": [ { "text": "Group 1", "children": [ { "id": 1, "text": "Option 1.1" }, { "id": 2, "text": "Option 1.2" } ] }, { "text": "Group 2", "children": [ { "id": 3, "text": "Option 2.1" }, { "id": 4, "text": "Option 2.2" } ] } ], "pagination": { "more": true } } ``` -------------------------------- ### Check Select2 Initialization Source: https://select2.org/programmatic-control/methods Tests if Select2 is initialized by checking for the select2-hidden-accessible class. ```javascript if ($('#mySelect2').hasClass("select2-hidden-accessible")) { // Select2 has been initialized } ``` -------------------------------- ### Custom Tag Properties Source: https://select2.org/tagging Use the createTag callback to add custom properties or metadata to newly created tags. ```javascript $('select').select2({ createTag: function(params) { var term = $.trim(params.term); if (term === '') { return null; } return { id: term, text: term, newTag: true // add additional parameters } } }); ``` -------------------------------- ### Set nested global default option Source: https://select2.org/configuration/defaults?q= Uses dash notation to set nested options, where double dashes represent nesting levels. ```javascript $.fn.select2.defaults.set("ajax--cache", false); ``` -------------------------------- ### Define a placeholder with an ID Source: https://select2.org/upgrading/migrating-from-35?q= Use an object with an id property to specify which option value acts as the placeholder. ```html ``` ```javascript $("select").select2({ placeholder: { id: "-1", placeholder: "Select an option" } }); ``` -------------------------------- ### Customize placeholder appearance Source: https://select2.org/placeholders?q= Uses templateSelection to apply custom logic or styling to the placeholder text in single-selection mode. ```javascript $('select').select2({ templateSelection: function(data) { if (data.id === '') { // adjust for custom placeholder values return 'Custom styled placeholder text'; } return data.text; } }); ``` -------------------------------- ### Implement the SelectionAdapter interface Source: https://select2.org/advanced/adapters-and-decorators?q= Required method for overriding the default selection display behavior in Select2. ```javascript // Update the selected data. // // @param data An array of data objects that have been generated by the data // adapter. If no objects should be selected, an empty array will be passed. // // Note: An array will always be passed into this method, even if Select2 is // attached to a source which only accepts a single selection. SelectionAdapter.update = function(data) {}; ``` -------------------------------- ### Generate dynamic URLs for AJAX Source: https://select2.org/data-sources/ajax Provide a callback function to the ajax.url option to dynamically construct the request URL based on the current search term. ```javascript $('#mySelect2').select2({ ajax: { url: function(params) { return '/some/url/' + params.term; } } }); ``` -------------------------------- ### Integrate Select2 with Webpack Encore Source: https://select2.org/getting-started/installation Import the JavaScript and CSS modules into your Webpack-managed assets. ```javascript require('select2'); ``` ```scss @import '~select2'; ``` -------------------------------- ### Initialize Select2 with a specific language Source: https://select2.org/i18n Sets the language for Select2 messages using a language code string. ```javascript $(".js-example-language").select2({ language: "es" }); ``` -------------------------------- ### Modern select element declaration Source: https://select2.org/upgrading/migrating-from-35?q= The recommended replacement using a select element with pre-selected options to match the previous hidden input values. ```html ``` -------------------------------- ### Enable clearable selections Source: https://select2.org/selections Add a clear button to the select box by setting allowClear to true. A placeholder must be defined for this functionality to work as expected. ```javascript $('select').select2({ placeholder: 'This is my placeholder', allowClear: true }); ``` -------------------------------- ### Initialize Select2 within a Bootstrap modal Source: https://select2.org/dropdown?q= Binds to the modal shown event to ensure Select2 is initialized with the correct dropdown parent when rendered inside a Bootstrap modal. ```javascript $('body').on('shown.bs.modal', '.modal', function() { $(this).find('select').each(function() { var dropdownParent = $(document.body); if ($(this).parents('.modal.in:first').length !== 0) dropdownParent = $(this).parents('.modal.in:first'); $(this).select2({ dropdownParent: dropdownParent // ... }); }); }); ``` -------------------------------- ### Legacy initSelection implementation Source: https://select2.org/upgrading/migrating-from-35?q= The deprecated initSelection option used in Select2 3.5 to convert input values into data objects. ```javascript { initSelection: function(element, callback) { var data = []; $(element.val()).each(function() { data.push({ id: this, text: this }); }); callback(data); } } ``` -------------------------------- ### Customize Tag Placement Source: https://select2.org/tagging Define the insertTag callback to control where new tags appear within the results list. ```javascript $('select').select2({ insertTag: function(data, tag) { // Insert the tag at the end of the results data.push(tag); } }); ``` -------------------------------- ### Select options programmatically Source: https://select2.org/programmatic-control/add-select-clear-items Use the jQuery .val() method to select single or multiple options, followed by a change event trigger. ```javascript $('#mySelect2').val('1'); // Select the option with a value of '1' $('#mySelect2').trigger('change'); // Notify any JS components that the value changed ``` ```javascript $('#mySelect2').val(['1', '2']); $('#mySelect2').trigger('change'); // Notify any JS components that the value changed ``` -------------------------------- ### Responsive Select2 HTML Structure Source: https://select2.org/appearance Define select elements with inline style attributes to ensure consistent width resolution. ```html ``` -------------------------------- ### Accessing Event Data Source: https://select2.org/programmatic-control/events?q= How to retrieve selection data from the event object when an event is triggered. ```APIDOC ## Event data ### Description When an event like `select2:select` is triggered, selection data is available via the `params.data` property. ### Example ```javascript $('#mySelect2').on('select2:select', function(e) { var data = e.params.data; console.log(data); }); ``` ``` -------------------------------- ### Preselect options in AJAX-sourced Select2 Source: https://select2.org/programmatic-control/add-select-clear-items For AJAX-sourced data, fetch the item individually and append it as a new option to ensure it exists before selection. ```javascript // Set up the Select2 control $('#mySelect2').select2({ ajax: { url: '/api/students' } }); // Fetch the preselected item, and add to the control var studentSelect = $('#mySelect2'); $.ajax({ type: 'GET', url: '/api/students/s/' + studentId }).then(function(data) { // create the option and append to Select2 var option = new Option(data.full_name, data.id, true, true); studentSelect.append(option).trigger('change'); // manually trigger the `select2:select` event studentSelect.trigger({ type: 'select2:select', params: { data: data } }); }); ``` -------------------------------- ### Create new options in Select2 Source: https://select2.org/programmatic-control/add-select-clear-items Create a new Option object and append it to the control to add items programmatically. ```javascript var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change'); ``` -------------------------------- ### Listening for Select2 Events Source: https://select2.org/programmatic-control/events?q= Attach event listeners to the Select2 element using the standard jQuery .on method. ```javascript $('#mySelect2').on('select2:select', function(e) { // Do something }); ``` -------------------------------- ### Basic Tagging HTML Structure Source: https://select2.org/tagging The standard HTML select element structure used for a tagging-enabled Select2 component. ```html ``` -------------------------------- ### Setting default pre-selected values Source: https://select2.org/data-sources/ajax Include option elements with the selected attribute to define initial values for AJAX-loaded Select2 controls. ```html ``` -------------------------------- ### Retrieve custom data attributes from selections Source: https://select2.org/programmatic-control/retrieving-selections?q= Demonstrates adding custom data attributes to option elements via templateSelection and retrieving them using jQuery. ```javascript $('#mySelect2').select2({ // ... templateSelection: function(data, container) { // Add custom attributes to the