0
# Initialization and Control
1
2
Core jQuery plugin methods for initializing Select2, calling instance methods, and managing global defaults.
3
4
## Capabilities
5
6
### Basic Initialization
7
8
Initialize Select2 on jQuery-selected elements with optional configuration.
9
10
```javascript { .api }
11
/**
12
* Initialize Select2 on selected elements
13
* @param options - Configuration options for Select2 behavior
14
* @returns jQuery object for chaining
15
*/
16
$.fn.select2(options?: Select2Options): jQuery;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
// Basic initialization with default settings
23
$('#basic-select').select2();
24
25
// Initialize with placeholder
26
$('#placeholder-select').select2({
27
placeholder: "Choose an option",
28
allowClear: true
29
});
30
31
// Multiple initialization
32
$('.multi-select').select2({
33
multiple: true,
34
width: '100%'
35
});
36
```
37
38
### Instance Method Calls
39
40
Call methods on already-initialized Select2 instances.
41
42
```javascript { .api }
43
/**
44
* Call instance methods on initialized Select2 elements
45
* @param method - Method name to call
46
* @returns jQuery object for chaining or method return value
47
*/
48
$.fn.select2(method: 'open' | 'close' | 'destroy' | 'focus' | 'enable'): jQuery;
49
$.fn.select2(method: 'data'): DataObject[];
50
$.fn.select2(method: 'isEnabled' | 'isDisabled' | 'isOpen' | 'hasFocus'): boolean;
51
```
52
53
**Available Methods:**
54
55
- `'open'` - Opens the dropdown menu
56
- `'close'` - Closes the dropdown menu
57
- `'destroy'` - Destroys the Select2 instance and restores original select
58
- `'data'` - Returns current selection data as array of DataObject
59
- `'focus'` - Programmatically focus the Select2 element
60
- `'enable'` - Enables the Select2 element (opposite of disabled)
61
- `'isEnabled'` - Returns true if the Select2 element is enabled
62
- `'isDisabled'` - Returns true if the Select2 element is disabled
63
- `'isOpen'` - Returns true if the dropdown is currently open
64
- `'hasFocus'` - Returns true if the Select2 element has focus
65
66
**Usage Examples:**
67
68
```javascript
69
// Open dropdown programmatically
70
$('#my-select').select2('open');
71
72
// Close dropdown
73
$('#my-select').select2('close');
74
75
// Get current selection data
76
var selectedData = $('#my-select').select2('data');
77
console.log(selectedData); // Array of DataObject
78
79
// Destroy instance
80
$('#my-select').select2('destroy');
81
82
// Focus the Select2 element
83
$('#my-select').select2('focus');
84
85
// Enable a disabled Select2 element
86
$('#my-select').select2('enable');
87
88
// Check element state
89
var isEnabled = $('#my-select').select2('isEnabled');
90
var isDisabled = $('#my-select').select2('isDisabled');
91
var isOpen = $('#my-select').select2('isOpen');
92
var hasFocus = $('#my-select').select2('hasFocus');
93
94
console.log('Enabled:', isEnabled);
95
console.log('Has focus:', hasFocus);
96
```
97
98
### Global Defaults Management
99
100
Manage global default configuration that applies to all new Select2 instances.
101
102
```javascript { .api }
103
/**
104
* Global defaults manager for Select2 configuration
105
*/
106
interface DefaultsManager {
107
/**
108
* Set a global default value
109
* @param key - Configuration key to set
110
* @param value - Default value to assign
111
*/
112
set(key: string, value: any): void;
113
114
/**
115
* Reset all defaults to original values
116
*/
117
reset(): void;
118
}
119
120
// Access global defaults
121
$.fn.select2.defaults: DefaultsManager;
122
```
123
124
**Usage Examples:**
125
126
```javascript
127
// Set global default placeholder
128
$.fn.select2.defaults.set('placeholder', 'Select an option...');
129
130
// Set global theme
131
$.fn.select2.defaults.set('theme', 'bootstrap4');
132
133
// Reset all defaults
134
$.fn.select2.defaults.reset();
135
```
136
137
### Value Management
138
139
Get and set values using standard jQuery methods with proper change triggering.
140
141
```javascript { .api }
142
/**
143
* Get or set select values using jQuery val() method
144
* Always trigger 'change' event after setting values
145
*/
146
// Get current value
147
$(selector).val(): string | string[];
148
149
// Set value and trigger change
150
$(selector).val(newValue).trigger('change'): jQuery;
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
// Get current value
157
var currentValue = $('#my-select').val();
158
159
// Set single value
160
$('#my-select').val('option1').trigger('change');
161
162
// Set multiple values
163
$('#multi-select').val(['option1', 'option2']).trigger('change');
164
165
// Clear selection
166
$('#my-select').val(null).trigger('change');
167
```
168
169
### Dynamic Option Management
170
171
Add, remove, and modify options dynamically after initialization.
172
173
```javascript { .api }
174
/**
175
* Add new options dynamically
176
* Create Option elements and append to select, then trigger change
177
*/
178
// Create and add new option
179
var newOption = new Option(text, value, defaultSelected, selected);
180
$(selector).append(newOption).trigger('change');
181
182
// Remove options
183
$(selector).find('option[value="optionValue"]').remove();
184
$(selector).trigger('change');
185
```
186
187
**Usage Examples:**
188
189
```javascript
190
// Add new option
191
var newOption = new Option("New Item", "new-value", false, false);
192
$('#my-select').append(newOption).trigger('change');
193
194
// Add and select new option
195
var selectedOption = new Option("Selected Item", "selected-value", false, true);
196
$('#my-select').append(selectedOption).trigger('change');
197
198
// Remove option by value
199
$('#my-select').find('option[value="remove-me"]').remove();
200
$('#my-select').trigger('change');
201
202
// Add multiple options
203
var options = [
204
new Option("Option 1", "opt1"),
205
new Option("Option 2", "opt2")
206
];
207
$('#my-select').append(options).trigger('change');
208
```
209
210
### Instance State Checking
211
212
Check the current state of Select2 instances using the internal API.
213
214
**Usage Examples:**
215
216
```javascript
217
// Check if Select2 is initialized
218
var isInitialized = $('#my-select').hasClass('select2-hidden-accessible');
219
220
// Access Select2 instance data
221
var select2Instance = $('#my-select').data('select2');
222
223
// Check if dropdown is open
224
var isOpen = $('#my-select').parent().find('.select2-dropdown').length > 0;
225
```
226
227
## Error Handling
228
229
Common error scenarios and their handling:
230
231
```javascript
232
// Check if element exists before initialization
233
if ($('#my-select').length > 0) {
234
$('#my-select').select2();
235
}
236
237
// Handle method calls on uninitialized elements
238
try {
239
$('#my-select').select2('open');
240
} catch (error) {
241
console.error('Select2 not initialized:', error);
242
}
243
244
// Check for Select2 initialization before calling methods
245
if ($('#my-select').data('select2')) {
246
$('#my-select').select2('data');
247
}
248
```