Initial commit

This commit is contained in:
meusinfirmary
2025-04-22 14:33:37 +07:00
commit b9891d2f81
1305 changed files with 452033 additions and 0 deletions

View File

@ -0,0 +1,101 @@
---
title: Add, select, or clear items
metadata:
description: Programmatically adding, selecting, and clearing options in a Select2 control.
taxonomy:
category: docs
---
## Creating new options in the dropdown
New options can be added to a Select2 control programmatically by creating a new [Javascript `Option` object](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option) and appending it to the control:
```
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
```
The third parameter of `new Option(...)` determines whether the item is "default selected"; i.e. it sets the `selected` attribute for the new option. The fourth parameter sets the options actual selected state - if set to `true`, the new option will be selected by default.
### Create if not exists
You can use `.find` to select the option if it already exists, and create it otherwise:
```
// 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');
}
```
## Selecting options
To programmatically select an option/item for a Select2 control, use the jQuery `.val()` method:
```
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
```
You can also pass an array to `val` make multiple selections:
```
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
```
Select2 will listen for the `change` event on the `<select>` element that it is attached to. When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.
### Preselecting options in an remotely-sourced (AJAX) Select2
For Select2 controls that receive their data from an [AJAX source](/data-sources/ajax), using `.val()` will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching. This is further complicated by server-side filtering and pagination - there is no guarantee when a particular item will actually be loaded into the Select2 control!
The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:
```
// 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
}
});
});
```
Notice that we manually trigger the `select2:select` event and pass along the entire `data` object. This allows other handlers to [access additional properties of the selected item](/programmatic-control/events#triggering-events).
## Clearing selections
You may clear all current selections in a Select2 control by setting the value of the control to `null`:
```
$('#mySelect2').val(null).trigger('change');
```

View File

@ -0,0 +1,43 @@
---
title: Retrieving selections
metadata:
description: There are two ways to programmatically access the current selection data: using `.select2('data')`, or by using a jQuery selector.
taxonomy:
category: docs
---
There are two ways to programmatically access the current selection data: using `.select2('data')`, or by using a jQuery selector.
## Using the `data` method
Calling `select2('data')` will return a JavaScript array of objects representing the current selection. Each object will contain all of the properties/values that were in the source data objects passed through `processResults` and `templateResult` callbacks.
```
$('#mySelect2').select2('data');
```
## Using a jQuery selector
Selected items can also be accessed via the `:selected` jQuery selector:
```
$('#mySelect2').find(':selected');
```
It is possible to extend the `<option>` elements representing the current selection(s) with HTML `data-*` attributes to contain arbitrary data from the source data objects:
```
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
```
>>>> Do not rely on the `selected` attribute of `<option>` elements to determine the currently selected item(s). Select2 does not add the `selected` attribute when an element is created from a remotely-sourced option. See [this issue](https://github.com/select2/select2/issues/3366#issuecomment-102566500) for more information.

View File

@ -0,0 +1,152 @@
---
title: Methods
metadata:
description: Select2 has several built-in methods that allow programmatic control of the component.
taxonomy:
category: docs
process:
twig: true
never_cache_twig: true
---
Select2 has several built-in methods that allow programmatic control of the component.
## Opening the dropdown
Methods handled directly by Select2 can be invoked by passing the name of the method to `.select2(...)`.
The `open` method will cause the dropdown menu to open, displaying the selectable options:
```
$('#mySelect2').select2('open');
```
## Closing the dropdown
The `close` method will cause the dropdown menu to close, hiding the selectable options:
```
$('#mySelect2').select2('close');
```
## Checking if the plugin is initialized
To test whether Select2 has been initialized on a particular DOM element, you can check for the `select2-hidden-accessible` class:
```
if ($('#mySelect2').hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
}
```
See [this Stack Overflow answer](https://stackoverflow.com/a/29854133/2970321)).
## Destroying the Select2 control
The `destroy` method will remove the Select2 widget from the target element. It will revert back to a standard `select` control:
```
$('#mySelect2').select2('destroy');
```
### Event unbinding
When you destroy a Select2 control, Select2 will only unbind the events that were automatically bound by the plugin. Any events that you bind in your own code, **including any [Select2 events](/programmatic-control/events) that you explicitly bind,** will need to be unbound manually using the `.off` jQuery method:
```
// Set up a Select2 control
$('#example').select2();
// Bind an event
$('#example').on('select2:select', function (e) {
console.log('select event');
});
// Destroy Select2
$('#example').select2('destroy');
// Unbind the event
$('#example').off('select2:select');
```
## Examples
<div class="s2-example">
<label for="select2-single">Single select</label>
<button class="js-programmatic-set-val button" aria-label="Set Select2 option">
Set "California"
</button>
<button class="js-programmatic-open button">
Open
</button>
<button class="js-programmatic-close button">
Close
</button>
<button class="js-programmatic-destroy button">
Destroy
</button>
<button class="js-programmatic-init button">
Re-initialize
</button>
<p>
<select id="select2-single" class="js-example-programmatic js-states form-control"></select>
</p>
<label for="select2-multi">Multiple select</label>
<button type="button" class="js-programmatic-multi-set-val button" aria-label="Programmatically set Select2 options">
Set to California and Alabama
</button>
<button type="button" class="js-programmatic-multi-clear button" aria-label="Programmatically clear Select2 options">
Clear
</button>
<p>
<select id="select2-multi" class="js-example-programmatic-multi js-states form-control" multiple="multiple"></select>
</p>
</div>
<pre data-fill-from=".js-code-programmatic"></pre>
<script type="text/javascript" class="js-code-programmatic">
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");
});
</script>

View File

@ -0,0 +1,148 @@
---
title: Events
metadata:
description: Listening to Select2's built-in events, and manually triggering events on the Select2 component.
taxonomy:
category: docs
process:
twig: true
never_cache_twig: true
---
Select2 will trigger a few different events when different actions are taken using the component, allowing you to add custom hooks and perform actions. You may also manually trigger these events on a Select2 control using `.trigger`.
| Event | Description |
| ----- | ----------- |
| `change` | Triggered whenever an option is selected or removed. |
| `change.select2` | Scoped version of `change`. See [below](#limiting-the-scope-of-the-change-event) for more details. |
| `select2:closing` | Triggered before the dropdown is closed. This event can be prevented. |
| `select2:close` | Triggered whenever the dropdown is closed. `select2:closing` is fired before this and can be prevented. |
| `select2:opening` | Triggered before the dropdown is opened. This event can be prevented. |
| `select2:open` | Triggered whenever the dropdown is opened. `select2:opening` is fired before this and can be prevented. |
| `select2:selecting` | Triggered before a result is selected. This event can be prevented. |
| `select2:select` | Triggered whenever a result is selected. `select2:selecting` is fired before this and can be prevented. |
| `select2:unselecting` | Triggered before a selection is removed. This event can be prevented. |
| `select2:unselect` | Triggered whenever a selection is removed. `select2:unselecting` is fired before this and can be prevented. |
| `select2:clearing` | Triggered before all selections are cleared. This event can be prevented. |
| `select2:clear` | Triggered whenever all selections are cleared. `select2:clearing` is fired before this and can be prevented. |
## Listening for events
All public events are relayed using the jQuery event system, and they are triggered on the `<select>` element that Select2 is attached to. You can attach to them using the [`.on` method](https://api.jquery.com/on/) provided by jQuery:
```
$('#mySelect2').on('select2:select', function (e) {
// Do something
});
```
## Event data
When `select2:select` is triggered, data from the selection can be accessed via the `params.data` property:
```
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
```
`e.params.data` will return an object containing the selection properties. Any additional data for the selection that was provided in the [data source](/data-sources/formats) will be included in this object as well. For example:
```
{
"id": 1,
"text": "Tyto alba",
"genus": "Tyto",
"species": "alba"
}
```
## Triggering events
You can manually trigger events on a Select2 control using the jQuery [`trigger`](http://api.jquery.com/trigger/) method. However, if you want to pass some data to any handlers for the event, you need to construct a new [jQuery `Event` object](http://api.jquery.com/category/events/event-object/) and trigger on that:
```
var data = {
"id": 1,
"text": "Tyto alba",
"genus": "Tyto",
"species": "alba"
};
$('#mySelect2').trigger({
type: 'select2:select',
params: {
data: data
}
});
```
### Limiting the scope of the `change` event
It's common for other components to be listening to the `change` event, or for custom event handlers to be attached that may have side effects. To limit the scope to **only** notify Select2 of the change, use the `.select2` event namespace:
```
$('#mySelect2').val('US'); // Change the value or make some change to the internal state
$('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes
```
## Examples
<div class="s2-example">
<p>
<select class="js-states js-example-events form-control"></select>
</p>
<p>
<select class="js-states js-example-events form-control" multiple="multiple"></select>
</p>
</div>
<div class="s2-event-log">
<ul class="js-event-log"></ul>
</div>
<pre data-fill-from=".js-code-events"></pre>
<script type="text/javascript" class="js-code-events">
var $eventLog = $(".js-event-log");
var $eventSelect = $(".js-example-events");
$eventSelect.select2();
$eventSelect.on("select2:open", function (e) { log("select2:open", e); });
$eventSelect.on("select2:close", function (e) { log("select2:close", e); });
$eventSelect.on("select2:select", function (e) { log("select2:select", e); });
$eventSelect.on("select2:unselect", function (e) { log("select2:unselect", e); });
$eventSelect.on("change", function (e) { log("change"); });
function log (name, evt) {
if (!evt) {
var args = "{}";
} else {
var args = JSON.stringify(evt.params, function (key, value) {
if (value && value.nodeName) return "[DOM node]";
if (value instanceof $.Event) return "[$.Event]";
return value;
});
}
var $e = $("<li>" + name + " -> " + args + "</li>");
$eventLog.append($e);
$e.animate({ opacity: 1 }, 10000, 'linear', function () {
$e.animate({ opacity: 0 }, 2000, 'linear', function () {
$e.remove();
});
});
}
</script>
## Preventing events
See [https://stackoverflow.com/a/26706695/2970321](https://stackoverflow.com/a/26706695/2970321).
## Internal Select2 events
Select2 has an [internal event system](/advanced/default-adapters/selection#eventrelay) that works independently of the DOM event system, allowing adapters to communicate with each other. This internal event system is only accessible from plugins and adapters that are connected to Select2 - **not** through the jQuery event system.
You can find more information on the public events triggered by individual adapters in the [advanced chapter](/advanced).

View File

@ -0,0 +1,9 @@
---
title: Programmatic control
metadata:
description: Programmatically adding and selecting items, getting the current selections, manipulating the control, and working with Select2 events.
taxonomy:
category: docs
---
# Programmatic control