Select2 is a jQuery based replacement for select boxes with searching, remote data sets, and infinite scrolling support
—
Data handling system supporting static arrays, HTML options, AJAX sources, and custom data adapters with standardized object formats.
Standard data format used throughout Select2 for representing options and selections.
/**
* Standard data object format
*/
interface DataObject {
id: string | number; // Unique identifier (required)
text: string; // Display text (required)
selected?: boolean; // Pre-selected state
disabled?: boolean; // Disabled state
element?: HTMLOptionElement; // Reference to HTML option element
}
/**
* Grouped data object format
*/
interface GroupedDataObject {
text: string; // Group label
children: DataObject[]; // Array of options in group
}Provide data as static arrays of objects for simple data sources.
/**
* Static data configuration
*/
data?: DataObject[] | GroupedDataObject[];Usage Examples:
// Simple data array
$('#static-select').select2({
data: [
{ id: '1', text: 'Option 1' },
{ id: '2', text: 'Option 2' },
{ id: '3', text: 'Option 3', selected: true },
{ id: '4', text: 'Option 4', disabled: true }
]
});
// Grouped data
$('#grouped-select').select2({
data: [
{
text: 'Group 1',
children: [
{ id: '1-1', text: 'Option 1.1' },
{ id: '1-2', text: 'Option 1.2' }
]
},
{
text: 'Group 2',
children: [
{ id: '2-1', text: 'Option 2.1' },
{ id: '2-2', text: 'Option 2.2' }
]
}
]
});
// Mixed flat and grouped data
$('#mixed-select').select2({
data: [
{ id: 'single', text: 'Single Option' },
{
text: 'Grouped Options',
children: [
{ id: 'g1', text: 'Group Item 1' },
{ id: 'g2', text: 'Group Item 2' }
]
}
]
});Use existing HTML option elements as the data source (default behavior).
<!-- HTML markup for data source -->
<select id="html-select">
<option value="">Choose...</option>
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" disabled>Option 3</option>
<optgroup label="Group 1">
<option value="g1">Group Option 1</option>
<option value="g2">Group Option 2</option>
</optgroup>
</select>/**
* HTML options are automatically converted to DataObject format
*/
// Initialization automatically reads HTML options
$('#html-select').select2();
// Access converted data
var data = $('#html-select').select2('data');
// Returns: [{ id: '2', text: 'Option 2', selected: true, element: HTMLOptionElement }]Add, remove, and update data after initialization.
/**
* Dynamic data manipulation methods
*/
// Add new options
var newOption = new Option(text: string, value: string, defaultSelected?: boolean, selected?: boolean);
$(selector).append(newOption).trigger('change');
// Remove options
$(selector).find('option[value="optionValue"]').remove().trigger('change');
// Update option text
$(selector).find('option[value="optionValue"]').text('New Text').trigger('change');
// Clear all options
$(selector).empty().trigger('change');
// Replace all data
$(selector).empty();
// Add new options...
$(selector).trigger('change');Usage Examples:
// Add single option
var newOption = new Option('New Item', 'new-id', false, false);
$('#dynamic-select').append(newOption).trigger('change');
// Add multiple options
var options = [
new Option('Item A', 'a'),
new Option('Item B', 'b'),
new Option('Item C', 'c')
];
$('#dynamic-select').append(options).trigger('change');
// Remove specific option
$('#dynamic-select').find('option[value="remove-me"]').remove().trigger('change');
// Update existing option
$('#dynamic-select').find('option[value="update-me"]')
.text('Updated Text')
.trigger('change');
// Replace all data
$('#dynamic-select').empty();
var freshData = [
new Option('Fresh 1', '1'),
new Option('Fresh 2', '2')
];
$('#dynamic-select').append(freshData).trigger('change');Get current selection data and available options.
/**
* Data retrieval methods
*/
// Get current selection data
$(selector).select2('data'): DataObject[];
// Get current values
$(selector).val(): string | string[] | null;
// Get all available options
$(selector).find('option'): jQuery;
// Get selected options
$(selector).find('option:selected'): jQuery;Usage Examples:
// Get current selection as data objects
var selectedData = $('#my-select').select2('data');
console.log(selectedData);
// Single: [{ id: '1', text: 'Option 1', selected: true }]
// Multiple: [{ id: '1', text: 'Option 1' }, { id: '2', text: 'Option 2' }]
// Get current values
var values = $('#my-select').val();
console.log(values);
// Single: '1' or null
// Multiple: ['1', '2'] or []
// Get all option elements
var allOptions = $('#my-select').find('option');
allOptions.each(function() {
console.log(this.value, this.text);
});
// Get only selected options
var selectedOptions = $('#my-select').find('option:selected');
selectedOptions.each(function() {
console.log('Selected:', this.text);
});Ensure data conforms to expected formats and validate selections.
/**
* Data validation helpers
*/
// Validate data object format
function isValidDataObject(obj: any): obj is DataObject {
return obj &&
(typeof obj.id === 'string' || typeof obj.id === 'number') &&
typeof obj.text === 'string';
}
// Format raw data to DataObject
function formatAsDataObject(id: string | number, text: string, options?: Partial<DataObject>): DataObject {
return {
id: id,
text: text,
...options
};
}Usage Examples:
// Validate and format external data
function addExternalData(rawData) {
var formattedData = rawData.map(function(item) {
// Validate required fields
if (!item.id || !item.label) {
console.warn('Invalid data item:', item);
return null;
}
return {
id: String(item.id),
text: item.label,
selected: item.isSelected || false,
disabled: item.isDisabled || false
};
}).filter(Boolean); // Remove null items
// Add to select
formattedData.forEach(function(dataObj) {
var option = new Option(dataObj.text, dataObj.id, dataObj.selected, dataObj.selected);
if (dataObj.disabled) {
option.disabled = true;
}
$('#my-select').append(option);
});
$('#my-select').trigger('change');
}
// Validate current selection
function validateSelection() {
var data = $('#my-select').select2('data');
return data.every(function(item) {
return isValidDataObject(item) && item.id !== '';
});
}Transform data between different formats for integration with external systems.
/**
* Data transformation utilities
*/
// Convert Select2 data to simple key-value pairs
function dataToKeyValue(data: DataObject[]): { [key: string]: string } {
var result = {};
data.forEach(function(item) {
result[item.id] = item.text;
});
return result;
}
// Convert external format to Select2 data
function externalToSelect2Data(external: any[]): DataObject[] {
return external.map(function(item) {
return {
id: item.value || item.id,
text: item.label || item.name || item.text,
selected: item.selected || false,
disabled: item.disabled || false
};
});
}Usage Examples:
// Export selection for form submission
function exportSelectionData() {
var selectedData = $('#my-select').select2('data');
// As simple values array
var values = selectedData.map(function(item) { return item.id; });
// As key-value object
var keyValue = {};
selectedData.forEach(function(item) {
keyValue[item.id] = item.text;
});
// As detailed objects
var detailed = selectedData.map(function(item) {
return {
value: item.id,
label: item.text,
metadata: {
selected: true,
disabled: item.disabled || false
}
};
});
return { values, keyValue, detailed };
}
// Import data from external API
function importExternalData(apiResponse) {
var select2Data = apiResponse.items.map(function(item) {
return {
id: item.id,
text: item.displayName,
selected: item.status === 'active',
disabled: item.status === 'archived'
};
});
// Clear existing options and add new data
$('#my-select').empty();
select2Data.forEach(function(dataObj) {
var option = new Option(dataObj.text, dataObj.id, dataObj.selected, dataObj.selected);
if (dataObj.disabled) option.disabled = true;
$('#my-select').append(option);
});
$('#my-select').trigger('change');
}Save and restore Select2 data state for user experience continuity.
// Save current state
function saveSelectState(selectId) {
var data = $(selectId).select2('data');
var values = $(selectId).val();
localStorage.setItem(selectId + '_data', JSON.stringify(data));
localStorage.setItem(selectId + '_values', JSON.stringify(values));
}
// Restore saved state
function restoreSelectState(selectId) {
var savedData = localStorage.getItem(selectId + '_data');
var savedValues = localStorage.getItem(selectId + '_values');
if (savedData && savedValues) {
var data = JSON.parse(savedData);
var values = JSON.parse(savedValues);
// Restore options if using data array
if (data.length > 0) {
$(selectId).empty();
data.forEach(function(item) {
var option = new Option(item.text, item.id, false, item.selected);
$(selectId).append(option);
});
}
// Set values and trigger change
$(selectId).val(values).trigger('change');
}
}Install with Tessl CLI
npx tessl i tessl/npm-select2