Select2 is a jQuery based replacement for select boxes with searching, remote data sets, and infinite scrolling support
—
Comprehensive event framework with lifecycle events, selection events, and preventable operations for full control over Select2 behavior.
All Select2 events are triggered on the original select element and follow a consistent naming pattern.
/**
* Core Select2 event types
*/
// Lifecycle Events
'select2:open' // Dropdown opened
'select2:opening' // Before dropdown opens (preventable)
'select2:close' // Dropdown closed
'select2:closing' // Before dropdown closes (preventable)
// Selection Events
'select2:select' // Item selected
'select2:selecting' // Before item selected (preventable)
'select2:unselect' // Item unselected (multi-select only)
'select2:unselecting' // Before item unselected (preventable)
// Clear Events
'select2:clear' // All selections cleared
'select2:clearing' // Before clearing all selections (preventable)
// Standard Events
'change' // Standard change event when selection changes
'change.select2' // Namespaced change eventAll Select2 events receive standardized event parameters.
/**
* Event parameter structure
*/
interface Select2Event {
type: string;
params: {
data?: DataObject; // Selected/unselected item data
originalEvent?: Event; // Original DOM event if applicable
args?: any[]; // Additional method arguments
};
target: HTMLElement; // Original select element
preventDefault: () => void; // Prevent event (for preventable events)
}
/**
* Data object structure in events
*/
interface DataObject {
id: string | number;
text: string;
selected?: boolean;
disabled?: boolean;
element?: HTMLOptionElement;
}Events that track the dropdown open/close lifecycle with prevention capabilities.
/**
* Lifecycle event handlers
*/
// Opening/open events
$(selector).on('select2:opening', function(e) {
// Fired before dropdown opens - can be prevented
e.preventDefault(); // Prevents dropdown from opening
});
$(selector).on('select2:open', function(e) {
// Fired after dropdown opens - cannot be prevented
});
// Closing/close events
$(selector).on('select2:closing', function(e) {
// Fired before dropdown closes - can be prevented
e.preventDefault(); // Prevents dropdown from closing
});
$(selector).on('select2:close', function(e) {
// Fired after dropdown closes - cannot be prevented
});Usage Examples:
// Prevent opening under certain conditions
$('#conditional-select').on('select2:opening', function(e) {
if (!userHasPermission) {
e.preventDefault();
alert('You do not have permission to use this dropdown');
}
});
// Track dropdown state
$('#tracked-select')
.on('select2:open', function(e) {
console.log('Dropdown opened');
$(this).addClass('dropdown-open');
})
.on('select2:close', function(e) {
console.log('Dropdown closed');
$(this).removeClass('dropdown-open');
});
// Conditional close prevention
$('#form-select').on('select2:closing', function(e) {
if (formHasUnsavedChanges) {
e.preventDefault();
if (!confirm('You have unsaved changes. Close anyway?')) {
return;
}
}
});Events triggered during item selection and deselection with access to the affected data.
/**
* Selection event handlers
*/
// Selection events
$(selector).on('select2:selecting', function(e) {
// Fired before item is selected - can be prevented
var data = e.params.data;
e.preventDefault(); // Prevents selection
});
$(selector).on('select2:select', function(e) {
// Fired after item is selected - cannot be prevented
var data = e.params.data;
});
// Unselection events (multi-select only)
$(selector).on('select2:unselecting', function(e) {
// Fired before item is unselected - can be prevented
var data = e.params.data;
e.preventDefault(); // Prevents unselection
});
$(selector).on('select2:unselect', function(e) {
// Fired after item is unselected - cannot be prevented
var data = e.params.data;
});Usage Examples:
// Validate selection
$('#validated-select').on('select2:selecting', function(e) {
var data = e.params.data;
if (data.id === 'forbidden-option') {
e.preventDefault();
alert('This option is not allowed');
return;
}
// Additional validation
if (!validateSelection(data)) {
e.preventDefault();
return;
}
});
// Track selections
$('#tracking-select').on('select2:select', function(e) {
var data = e.params.data;
console.log('Selected:', data.text, 'with ID:', data.id);
// Send analytics
analytics.track('option_selected', {
option_id: data.id,
option_text: data.text
});
});
// Confirm unselection
$('#confirm-unselect').on('select2:unselecting', function(e) {
var data = e.params.data;
if (!confirm('Remove "' + data.text + '"?')) {
e.preventDefault();
}
});
// Handle unselection
$('#multi-select').on('select2:unselect', function(e) {
var data = e.params.data;
console.log('Removed:', data.text);
});Events for handling the "clear all" functionality in single selects with allowClear enabled.
/**
* Clear event handlers
*/
$(selector).on('select2:clearing', function(e) {
// Fired before clearing selection - can be prevented
e.preventDefault(); // Prevents clearing
});
$(selector).on('select2:clear', function(e) {
// Fired after selection is cleared - cannot be prevented
});Usage Examples:
// Confirm before clearing
$('#confirm-clear').on('select2:clearing', function(e) {
if (!confirm('Clear selection?')) {
e.preventDefault();
}
});
// Track clearing
$('#tracked-clear').on('select2:clear', function(e) {
console.log('Selection cleared');
analytics.track('selection_cleared');
});Standard jQuery change events that fire when the select value changes.
/**
* Standard change event handlers
*/
$(selector).on('change', function(e) {
// Standard change event - fires when value changes
var currentValue = $(this).val();
});
$(selector).on('change.select2', function(e) {
// Namespaced change event - Select2 specific
var currentValue = $(this).val();
});Usage Examples:
// Handle value changes
$('#my-select').on('change', function(e) {
var selectedValue = $(this).val();
var selectedText = $(this).find('option:selected').text();
console.log('Value changed to:', selectedValue);
updateForm(selectedValue);
});
// Multiple change handling
$('#multi-select').on('change', function(e) {
var selectedValues = $(this).val() || [];
console.log('Selected values:', selectedValues);
if (selectedValues.length > 3) {
alert('Maximum 3 selections allowed');
// Truncate to 3 items
$(this).val(selectedValues.slice(0, 3)).trigger('change');
}
});Manually trigger Select2 events to programmatically control behavior.
/**
* Manual event triggering
*/
// Trigger with custom data
$(selector).trigger({
type: 'select2:select',
params: {
data: dataObject
}
});
// Trigger standard events
$(selector).trigger('change');
$(selector).val('newValue').trigger('change');Usage Examples:
// Programmatically select item
var dataObject = { id: '1', text: 'Option 1' };
$('#my-select').trigger({
type: 'select2:select',
params: {
data: dataObject
}
});
// Simulate user selection
$('#my-select').val('option1').trigger('change');
// Programmatically open dropdown
$('#my-select').select2('open');Handle events for dynamically created Select2 instances or multiple selects.
/**
* Event delegation patterns
*/
// Delegate events for dynamic elements
$(document).on('select2:select', '.dynamic-select', function(e) {
var data = e.params.data;
console.log('Dynamic select changed:', data);
});
// Handle multiple selects with same class
$('.all-selects').on('select2:open', function(e) {
console.log('One of the selects opened:', this.id);
});Usage Examples:
// Dynamic Select2 instances
$(document).on('select2:select', '.product-select', function(e) {
var productId = e.params.data.id;
var selectElement = $(this);
loadProductDetails(productId, function(details) {
selectElement.next('.product-details').html(details);
});
});
// Multiple form selects
$('.form-select').on('change', function(e) {
var formData = {};
$('.form-select').each(function() {
formData[this.name] = $(this).val();
});
validateForm(formData);
});Handle errors gracefully within event handlers.
// Safe event handling
$('#my-select').on('select2:select', function(e) {
try {
var data = e.params.data;
processSelection(data);
} catch (error) {
console.error('Error processing selection:', error);
// Optionally revert selection
}
});
// Async error handling
$('#async-select').on('select2:select', function(e) {
var data = e.params.data;
processSelectionAsync(data).catch(function(error) {
console.error('Async error:', error);
alert('Failed to process selection');
});
});Install with Tessl CLI
npx tessl i tessl/npm-select2