0
# Data Management
1
2
Data handling system supporting static arrays, HTML options, AJAX sources, and custom data adapters with standardized object formats.
3
4
## Capabilities
5
6
### Data Object Structure
7
8
Standard data format used throughout Select2 for representing options and selections.
9
10
```javascript { .api }
11
/**
12
* Standard data object format
13
*/
14
interface DataObject {
15
id: string | number; // Unique identifier (required)
16
text: string; // Display text (required)
17
selected?: boolean; // Pre-selected state
18
disabled?: boolean; // Disabled state
19
element?: HTMLOptionElement; // Reference to HTML option element
20
}
21
22
/**
23
* Grouped data object format
24
*/
25
interface GroupedDataObject {
26
text: string; // Group label
27
children: DataObject[]; // Array of options in group
28
}
29
```
30
31
### Static Data Arrays
32
33
Provide data as static arrays of objects for simple data sources.
34
35
```javascript { .api }
36
/**
37
* Static data configuration
38
*/
39
data?: DataObject[] | GroupedDataObject[];
40
```
41
42
**Usage Examples:**
43
44
```javascript
45
// Simple data array
46
$('#static-select').select2({
47
data: [
48
{ id: '1', text: 'Option 1' },
49
{ id: '2', text: 'Option 2' },
50
{ id: '3', text: 'Option 3', selected: true },
51
{ id: '4', text: 'Option 4', disabled: true }
52
]
53
});
54
55
// Grouped data
56
$('#grouped-select').select2({
57
data: [
58
{
59
text: 'Group 1',
60
children: [
61
{ id: '1-1', text: 'Option 1.1' },
62
{ id: '1-2', text: 'Option 1.2' }
63
]
64
},
65
{
66
text: 'Group 2',
67
children: [
68
{ id: '2-1', text: 'Option 2.1' },
69
{ id: '2-2', text: 'Option 2.2' }
70
]
71
}
72
]
73
});
74
75
// Mixed flat and grouped data
76
$('#mixed-select').select2({
77
data: [
78
{ id: 'single', text: 'Single Option' },
79
{
80
text: 'Grouped Options',
81
children: [
82
{ id: 'g1', text: 'Group Item 1' },
83
{ id: 'g2', text: 'Group Item 2' }
84
]
85
}
86
]
87
});
88
```
89
90
### HTML Option Data Source
91
92
Use existing HTML option elements as the data source (default behavior).
93
94
```html
95
<!-- HTML markup for data source -->
96
<select id="html-select">
97
<option value="">Choose...</option>
98
<option value="1">Option 1</option>
99
<option value="2" selected>Option 2</option>
100
<option value="3" disabled>Option 3</option>
101
<optgroup label="Group 1">
102
<option value="g1">Group Option 1</option>
103
<option value="g2">Group Option 2</option>
104
</optgroup>
105
</select>
106
```
107
108
```javascript { .api }
109
/**
110
* HTML options are automatically converted to DataObject format
111
*/
112
// Initialization automatically reads HTML options
113
$('#html-select').select2();
114
115
// Access converted data
116
var data = $('#html-select').select2('data');
117
// Returns: [{ id: '2', text: 'Option 2', selected: true, element: HTMLOptionElement }]
118
```
119
120
### Dynamic Data Manipulation
121
122
Add, remove, and update data after initialization.
123
124
```javascript { .api }
125
/**
126
* Dynamic data manipulation methods
127
*/
128
// Add new options
129
var newOption = new Option(text: string, value: string, defaultSelected?: boolean, selected?: boolean);
130
$(selector).append(newOption).trigger('change');
131
132
// Remove options
133
$(selector).find('option[value="optionValue"]').remove().trigger('change');
134
135
// Update option text
136
$(selector).find('option[value="optionValue"]').text('New Text').trigger('change');
137
138
// Clear all options
139
$(selector).empty().trigger('change');
140
141
// Replace all data
142
$(selector).empty();
143
// Add new options...
144
$(selector).trigger('change');
145
```
146
147
**Usage Examples:**
148
149
```javascript
150
// Add single option
151
var newOption = new Option('New Item', 'new-id', false, false);
152
$('#dynamic-select').append(newOption).trigger('change');
153
154
// Add multiple options
155
var options = [
156
new Option('Item A', 'a'),
157
new Option('Item B', 'b'),
158
new Option('Item C', 'c')
159
];
160
$('#dynamic-select').append(options).trigger('change');
161
162
// Remove specific option
163
$('#dynamic-select').find('option[value="remove-me"]').remove().trigger('change');
164
165
// Update existing option
166
$('#dynamic-select').find('option[value="update-me"]')
167
.text('Updated Text')
168
.trigger('change');
169
170
// Replace all data
171
$('#dynamic-select').empty();
172
var freshData = [
173
new Option('Fresh 1', '1'),
174
new Option('Fresh 2', '2')
175
];
176
$('#dynamic-select').append(freshData).trigger('change');
177
```
178
179
### Data Retrieval
180
181
Get current selection data and available options.
182
183
```javascript { .api }
184
/**
185
* Data retrieval methods
186
*/
187
// Get current selection data
188
$(selector).select2('data'): DataObject[];
189
190
// Get current values
191
$(selector).val(): string | string[] | null;
192
193
// Get all available options
194
$(selector).find('option'): jQuery;
195
196
// Get selected options
197
$(selector).find('option:selected'): jQuery;
198
```
199
200
**Usage Examples:**
201
202
```javascript
203
// Get current selection as data objects
204
var selectedData = $('#my-select').select2('data');
205
console.log(selectedData);
206
// Single: [{ id: '1', text: 'Option 1', selected: true }]
207
// Multiple: [{ id: '1', text: 'Option 1' }, { id: '2', text: 'Option 2' }]
208
209
// Get current values
210
var values = $('#my-select').val();
211
console.log(values);
212
// Single: '1' or null
213
// Multiple: ['1', '2'] or []
214
215
// Get all option elements
216
var allOptions = $('#my-select').find('option');
217
allOptions.each(function() {
218
console.log(this.value, this.text);
219
});
220
221
// Get only selected options
222
var selectedOptions = $('#my-select').find('option:selected');
223
selectedOptions.each(function() {
224
console.log('Selected:', this.text);
225
});
226
```
227
228
### Data Validation and Formatting
229
230
Ensure data conforms to expected formats and validate selections.
231
232
```javascript { .api }
233
/**
234
* Data validation helpers
235
*/
236
// Validate data object format
237
function isValidDataObject(obj: any): obj is DataObject {
238
return obj &&
239
(typeof obj.id === 'string' || typeof obj.id === 'number') &&
240
typeof obj.text === 'string';
241
}
242
243
// Format raw data to DataObject
244
function formatAsDataObject(id: string | number, text: string, options?: Partial<DataObject>): DataObject {
245
return {
246
id: id,
247
text: text,
248
...options
249
};
250
}
251
```
252
253
**Usage Examples:**
254
255
```javascript
256
// Validate and format external data
257
function addExternalData(rawData) {
258
var formattedData = rawData.map(function(item) {
259
// Validate required fields
260
if (!item.id || !item.label) {
261
console.warn('Invalid data item:', item);
262
return null;
263
}
264
265
return {
266
id: String(item.id),
267
text: item.label,
268
selected: item.isSelected || false,
269
disabled: item.isDisabled || false
270
};
271
}).filter(Boolean); // Remove null items
272
273
// Add to select
274
formattedData.forEach(function(dataObj) {
275
var option = new Option(dataObj.text, dataObj.id, dataObj.selected, dataObj.selected);
276
if (dataObj.disabled) {
277
option.disabled = true;
278
}
279
$('#my-select').append(option);
280
});
281
282
$('#my-select').trigger('change');
283
}
284
285
// Validate current selection
286
function validateSelection() {
287
var data = $('#my-select').select2('data');
288
289
return data.every(function(item) {
290
return isValidDataObject(item) && item.id !== '';
291
});
292
}
293
```
294
295
### Data Transformation
296
297
Transform data between different formats for integration with external systems.
298
299
```javascript { .api }
300
/**
301
* Data transformation utilities
302
*/
303
// Convert Select2 data to simple key-value pairs
304
function dataToKeyValue(data: DataObject[]): { [key: string]: string } {
305
var result = {};
306
data.forEach(function(item) {
307
result[item.id] = item.text;
308
});
309
return result;
310
}
311
312
// Convert external format to Select2 data
313
function externalToSelect2Data(external: any[]): DataObject[] {
314
return external.map(function(item) {
315
return {
316
id: item.value || item.id,
317
text: item.label || item.name || item.text,
318
selected: item.selected || false,
319
disabled: item.disabled || false
320
};
321
});
322
}
323
```
324
325
**Usage Examples:**
326
327
```javascript
328
// Export selection for form submission
329
function exportSelectionData() {
330
var selectedData = $('#my-select').select2('data');
331
332
// As simple values array
333
var values = selectedData.map(function(item) { return item.id; });
334
335
// As key-value object
336
var keyValue = {};
337
selectedData.forEach(function(item) {
338
keyValue[item.id] = item.text;
339
});
340
341
// As detailed objects
342
var detailed = selectedData.map(function(item) {
343
return {
344
value: item.id,
345
label: item.text,
346
metadata: {
347
selected: true,
348
disabled: item.disabled || false
349
}
350
};
351
});
352
353
return { values, keyValue, detailed };
354
}
355
356
// Import data from external API
357
function importExternalData(apiResponse) {
358
var select2Data = apiResponse.items.map(function(item) {
359
return {
360
id: item.id,
361
text: item.displayName,
362
selected: item.status === 'active',
363
disabled: item.status === 'archived'
364
};
365
});
366
367
// Clear existing options and add new data
368
$('#my-select').empty();
369
370
select2Data.forEach(function(dataObj) {
371
var option = new Option(dataObj.text, dataObj.id, dataObj.selected, dataObj.selected);
372
if (dataObj.disabled) option.disabled = true;
373
$('#my-select').append(option);
374
});
375
376
$('#my-select').trigger('change');
377
}
378
```
379
380
### Data Persistence
381
382
Save and restore Select2 data state for user experience continuity.
383
384
```javascript
385
// Save current state
386
function saveSelectState(selectId) {
387
var data = $(selectId).select2('data');
388
var values = $(selectId).val();
389
390
localStorage.setItem(selectId + '_data', JSON.stringify(data));
391
localStorage.setItem(selectId + '_values', JSON.stringify(values));
392
}
393
394
// Restore saved state
395
function restoreSelectState(selectId) {
396
var savedData = localStorage.getItem(selectId + '_data');
397
var savedValues = localStorage.getItem(selectId + '_values');
398
399
if (savedData && savedValues) {
400
var data = JSON.parse(savedData);
401
var values = JSON.parse(savedValues);
402
403
// Restore options if using data array
404
if (data.length > 0) {
405
$(selectId).empty();
406
data.forEach(function(item) {
407
var option = new Option(item.text, item.id, false, item.selected);
408
$(selectId).append(option);
409
});
410
}
411
412
// Set values and trigger change
413
$(selectId).val(values).trigger('change');
414
}
415
}
416
```