0
# Event System
1
2
Comprehensive event framework with lifecycle events, selection events, and preventable operations for full control over Select2 behavior.
3
4
## Capabilities
5
6
### Core Event Types
7
8
All Select2 events are triggered on the original select element and follow a consistent naming pattern.
9
10
```javascript { .api }
11
/**
12
* Core Select2 event types
13
*/
14
// Lifecycle Events
15
'select2:open' // Dropdown opened
16
'select2:opening' // Before dropdown opens (preventable)
17
'select2:close' // Dropdown closed
18
'select2:closing' // Before dropdown closes (preventable)
19
20
// Selection Events
21
'select2:select' // Item selected
22
'select2:selecting' // Before item selected (preventable)
23
'select2:unselect' // Item unselected (multi-select only)
24
'select2:unselecting' // Before item unselected (preventable)
25
26
// Clear Events
27
'select2:clear' // All selections cleared
28
'select2:clearing' // Before clearing all selections (preventable)
29
30
// Standard Events
31
'change' // Standard change event when selection changes
32
'change.select2' // Namespaced change event
33
```
34
35
### Event Data Structure
36
37
All Select2 events receive standardized event parameters.
38
39
```javascript { .api }
40
/**
41
* Event parameter structure
42
*/
43
interface Select2Event {
44
type: string;
45
params: {
46
data?: DataObject; // Selected/unselected item data
47
originalEvent?: Event; // Original DOM event if applicable
48
args?: any[]; // Additional method arguments
49
};
50
target: HTMLElement; // Original select element
51
preventDefault: () => void; // Prevent event (for preventable events)
52
}
53
54
/**
55
* Data object structure in events
56
*/
57
interface DataObject {
58
id: string | number;
59
text: string;
60
selected?: boolean;
61
disabled?: boolean;
62
element?: HTMLOptionElement;
63
}
64
```
65
66
### Lifecycle Events
67
68
Events that track the dropdown open/close lifecycle with prevention capabilities.
69
70
```javascript { .api }
71
/**
72
* Lifecycle event handlers
73
*/
74
// Opening/open events
75
$(selector).on('select2:opening', function(e) {
76
// Fired before dropdown opens - can be prevented
77
e.preventDefault(); // Prevents dropdown from opening
78
});
79
80
$(selector).on('select2:open', function(e) {
81
// Fired after dropdown opens - cannot be prevented
82
});
83
84
// Closing/close events
85
$(selector).on('select2:closing', function(e) {
86
// Fired before dropdown closes - can be prevented
87
e.preventDefault(); // Prevents dropdown from closing
88
});
89
90
$(selector).on('select2:close', function(e) {
91
// Fired after dropdown closes - cannot be prevented
92
});
93
```
94
95
**Usage Examples:**
96
97
```javascript
98
// Prevent opening under certain conditions
99
$('#conditional-select').on('select2:opening', function(e) {
100
if (!userHasPermission) {
101
e.preventDefault();
102
alert('You do not have permission to use this dropdown');
103
}
104
});
105
106
// Track dropdown state
107
$('#tracked-select')
108
.on('select2:open', function(e) {
109
console.log('Dropdown opened');
110
$(this).addClass('dropdown-open');
111
})
112
.on('select2:close', function(e) {
113
console.log('Dropdown closed');
114
$(this).removeClass('dropdown-open');
115
});
116
117
// Conditional close prevention
118
$('#form-select').on('select2:closing', function(e) {
119
if (formHasUnsavedChanges) {
120
e.preventDefault();
121
if (!confirm('You have unsaved changes. Close anyway?')) {
122
return;
123
}
124
}
125
});
126
```
127
128
### Selection Events
129
130
Events triggered during item selection and deselection with access to the affected data.
131
132
```javascript { .api }
133
/**
134
* Selection event handlers
135
*/
136
// Selection events
137
$(selector).on('select2:selecting', function(e) {
138
// Fired before item is selected - can be prevented
139
var data = e.params.data;
140
e.preventDefault(); // Prevents selection
141
});
142
143
$(selector).on('select2:select', function(e) {
144
// Fired after item is selected - cannot be prevented
145
var data = e.params.data;
146
});
147
148
// Unselection events (multi-select only)
149
$(selector).on('select2:unselecting', function(e) {
150
// Fired before item is unselected - can be prevented
151
var data = e.params.data;
152
e.preventDefault(); // Prevents unselection
153
});
154
155
$(selector).on('select2:unselect', function(e) {
156
// Fired after item is unselected - cannot be prevented
157
var data = e.params.data;
158
});
159
```
160
161
**Usage Examples:**
162
163
```javascript
164
// Validate selection
165
$('#validated-select').on('select2:selecting', function(e) {
166
var data = e.params.data;
167
168
if (data.id === 'forbidden-option') {
169
e.preventDefault();
170
alert('This option is not allowed');
171
return;
172
}
173
174
// Additional validation
175
if (!validateSelection(data)) {
176
e.preventDefault();
177
return;
178
}
179
});
180
181
// Track selections
182
$('#tracking-select').on('select2:select', function(e) {
183
var data = e.params.data;
184
console.log('Selected:', data.text, 'with ID:', data.id);
185
186
// Send analytics
187
analytics.track('option_selected', {
188
option_id: data.id,
189
option_text: data.text
190
});
191
});
192
193
// Confirm unselection
194
$('#confirm-unselect').on('select2:unselecting', function(e) {
195
var data = e.params.data;
196
197
if (!confirm('Remove "' + data.text + '"?')) {
198
e.preventDefault();
199
}
200
});
201
202
// Handle unselection
203
$('#multi-select').on('select2:unselect', function(e) {
204
var data = e.params.data;
205
console.log('Removed:', data.text);
206
});
207
```
208
209
### Clear Events
210
211
Events for handling the "clear all" functionality in single selects with allowClear enabled.
212
213
```javascript { .api }
214
/**
215
* Clear event handlers
216
*/
217
$(selector).on('select2:clearing', function(e) {
218
// Fired before clearing selection - can be prevented
219
e.preventDefault(); // Prevents clearing
220
});
221
222
$(selector).on('select2:clear', function(e) {
223
// Fired after selection is cleared - cannot be prevented
224
});
225
```
226
227
**Usage Examples:**
228
229
```javascript
230
// Confirm before clearing
231
$('#confirm-clear').on('select2:clearing', function(e) {
232
if (!confirm('Clear selection?')) {
233
e.preventDefault();
234
}
235
});
236
237
// Track clearing
238
$('#tracked-clear').on('select2:clear', function(e) {
239
console.log('Selection cleared');
240
analytics.track('selection_cleared');
241
});
242
```
243
244
### Standard Change Events
245
246
Standard jQuery change events that fire when the select value changes.
247
248
```javascript { .api }
249
/**
250
* Standard change event handlers
251
*/
252
$(selector).on('change', function(e) {
253
// Standard change event - fires when value changes
254
var currentValue = $(this).val();
255
});
256
257
$(selector).on('change.select2', function(e) {
258
// Namespaced change event - Select2 specific
259
var currentValue = $(this).val();
260
});
261
```
262
263
**Usage Examples:**
264
265
```javascript
266
// Handle value changes
267
$('#my-select').on('change', function(e) {
268
var selectedValue = $(this).val();
269
var selectedText = $(this).find('option:selected').text();
270
271
console.log('Value changed to:', selectedValue);
272
updateForm(selectedValue);
273
});
274
275
// Multiple change handling
276
$('#multi-select').on('change', function(e) {
277
var selectedValues = $(this).val() || [];
278
console.log('Selected values:', selectedValues);
279
280
if (selectedValues.length > 3) {
281
alert('Maximum 3 selections allowed');
282
// Truncate to 3 items
283
$(this).val(selectedValues.slice(0, 3)).trigger('change');
284
}
285
});
286
```
287
288
### Event Triggering
289
290
Manually trigger Select2 events to programmatically control behavior.
291
292
```javascript { .api }
293
/**
294
* Manual event triggering
295
*/
296
// Trigger with custom data
297
$(selector).trigger({
298
type: 'select2:select',
299
params: {
300
data: dataObject
301
}
302
});
303
304
// Trigger standard events
305
$(selector).trigger('change');
306
$(selector).val('newValue').trigger('change');
307
```
308
309
**Usage Examples:**
310
311
```javascript
312
// Programmatically select item
313
var dataObject = { id: '1', text: 'Option 1' };
314
$('#my-select').trigger({
315
type: 'select2:select',
316
params: {
317
data: dataObject
318
}
319
});
320
321
// Simulate user selection
322
$('#my-select').val('option1').trigger('change');
323
324
// Programmatically open dropdown
325
$('#my-select').select2('open');
326
```
327
328
### Event Delegation and Multiple Selects
329
330
Handle events for dynamically created Select2 instances or multiple selects.
331
332
```javascript { .api }
333
/**
334
* Event delegation patterns
335
*/
336
// Delegate events for dynamic elements
337
$(document).on('select2:select', '.dynamic-select', function(e) {
338
var data = e.params.data;
339
console.log('Dynamic select changed:', data);
340
});
341
342
// Handle multiple selects with same class
343
$('.all-selects').on('select2:open', function(e) {
344
console.log('One of the selects opened:', this.id);
345
});
346
```
347
348
**Usage Examples:**
349
350
```javascript
351
// Dynamic Select2 instances
352
$(document).on('select2:select', '.product-select', function(e) {
353
var productId = e.params.data.id;
354
var selectElement = $(this);
355
356
loadProductDetails(productId, function(details) {
357
selectElement.next('.product-details').html(details);
358
});
359
});
360
361
// Multiple form selects
362
$('.form-select').on('change', function(e) {
363
var formData = {};
364
$('.form-select').each(function() {
365
formData[this.name] = $(this).val();
366
});
367
368
validateForm(formData);
369
});
370
```
371
372
### Error Handling in Events
373
374
Handle errors gracefully within event handlers.
375
376
```javascript
377
// Safe event handling
378
$('#my-select').on('select2:select', function(e) {
379
try {
380
var data = e.params.data;
381
processSelection(data);
382
} catch (error) {
383
console.error('Error processing selection:', error);
384
// Optionally revert selection
385
}
386
});
387
388
// Async error handling
389
$('#async-select').on('select2:select', function(e) {
390
var data = e.params.data;
391
392
processSelectionAsync(data).catch(function(error) {
393
console.error('Async error:', error);
394
alert('Failed to process selection');
395
});
396
});
397
```