CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-select2

Select2 is a jQuery based replacement for select boxes with searching, remote data sets, and infinite scrolling support

Pending
Overview
Eval results
Files

initialization.mddocs/

Initialization and Control

Core jQuery plugin methods for initializing Select2, calling instance methods, and managing global defaults.

Capabilities

Basic Initialization

Initialize Select2 on jQuery-selected elements with optional configuration.

/**
 * Initialize Select2 on selected elements
 * @param options - Configuration options for Select2 behavior
 * @returns jQuery object for chaining
 */
$.fn.select2(options?: Select2Options): jQuery;

Usage Examples:

// Basic initialization with default settings
$('#basic-select').select2();

// Initialize with placeholder
$('#placeholder-select').select2({
    placeholder: "Choose an option",
    allowClear: true
});

// Multiple initialization
$('.multi-select').select2({
    multiple: true,
    width: '100%'
});

Instance Method Calls

Call methods on already-initialized Select2 instances.

/**
 * Call instance methods on initialized Select2 elements
 * @param method - Method name to call
 * @returns jQuery object for chaining or method return value
 */
$.fn.select2(method: 'open' | 'close' | 'destroy' | 'focus' | 'enable'): jQuery;
$.fn.select2(method: 'data'): DataObject[];
$.fn.select2(method: 'isEnabled' | 'isDisabled' | 'isOpen' | 'hasFocus'): boolean;

Available Methods:

  • 'open' - Opens the dropdown menu
  • 'close' - Closes the dropdown menu
  • 'destroy' - Destroys the Select2 instance and restores original select
  • 'data' - Returns current selection data as array of DataObject
  • 'focus' - Programmatically focus the Select2 element
  • 'enable' - Enables the Select2 element (opposite of disabled)
  • 'isEnabled' - Returns true if the Select2 element is enabled
  • 'isDisabled' - Returns true if the Select2 element is disabled
  • 'isOpen' - Returns true if the dropdown is currently open
  • 'hasFocus' - Returns true if the Select2 element has focus

Usage Examples:

// Open dropdown programmatically
$('#my-select').select2('open');

// Close dropdown
$('#my-select').select2('close');

// Get current selection data
var selectedData = $('#my-select').select2('data');
console.log(selectedData); // Array of DataObject

// Destroy instance
$('#my-select').select2('destroy');

// Focus the Select2 element
$('#my-select').select2('focus');

// Enable a disabled Select2 element
$('#my-select').select2('enable');

// Check element state
var isEnabled = $('#my-select').select2('isEnabled');
var isDisabled = $('#my-select').select2('isDisabled');
var isOpen = $('#my-select').select2('isOpen');
var hasFocus = $('#my-select').select2('hasFocus');

console.log('Enabled:', isEnabled);
console.log('Has focus:', hasFocus);

Global Defaults Management

Manage global default configuration that applies to all new Select2 instances.

/**
 * Global defaults manager for Select2 configuration
 */
interface DefaultsManager {
    /**
     * Set a global default value
     * @param key - Configuration key to set
     * @param value - Default value to assign
     */
    set(key: string, value: any): void;
    
    /**
     * Reset all defaults to original values
     */
    reset(): void;
}

// Access global defaults
$.fn.select2.defaults: DefaultsManager;

Usage Examples:

// Set global default placeholder
$.fn.select2.defaults.set('placeholder', 'Select an option...');

// Set global theme
$.fn.select2.defaults.set('theme', 'bootstrap4');

// Reset all defaults
$.fn.select2.defaults.reset();

Value Management

Get and set values using standard jQuery methods with proper change triggering.

/**
 * Get or set select values using jQuery val() method
 * Always trigger 'change' event after setting values
 */
// Get current value
$(selector).val(): string | string[];

// Set value and trigger change
$(selector).val(newValue).trigger('change'): jQuery;

Usage Examples:

// Get current value
var currentValue = $('#my-select').val();

// Set single value
$('#my-select').val('option1').trigger('change');

// Set multiple values
$('#multi-select').val(['option1', 'option2']).trigger('change');

// Clear selection
$('#my-select').val(null).trigger('change');

Dynamic Option Management

Add, remove, and modify options dynamically after initialization.

/**
 * Add new options dynamically
 * Create Option elements and append to select, then trigger change
 */
// Create and add new option
var newOption = new Option(text, value, defaultSelected, selected);
$(selector).append(newOption).trigger('change');

// Remove options
$(selector).find('option[value="optionValue"]').remove();
$(selector).trigger('change');

Usage Examples:

// Add new option
var newOption = new Option("New Item", "new-value", false, false);
$('#my-select').append(newOption).trigger('change');

// Add and select new option
var selectedOption = new Option("Selected Item", "selected-value", false, true);
$('#my-select').append(selectedOption).trigger('change');

// Remove option by value
$('#my-select').find('option[value="remove-me"]').remove();
$('#my-select').trigger('change');

// Add multiple options
var options = [
    new Option("Option 1", "opt1"),
    new Option("Option 2", "opt2")
];
$('#my-select').append(options).trigger('change');

Instance State Checking

Check the current state of Select2 instances using the internal API.

Usage Examples:

// Check if Select2 is initialized
var isInitialized = $('#my-select').hasClass('select2-hidden-accessible');

// Access Select2 instance data
var select2Instance = $('#my-select').data('select2');

// Check if dropdown is open
var isOpen = $('#my-select').parent().find('.select2-dropdown').length > 0;

Error Handling

Common error scenarios and their handling:

// Check if element exists before initialization
if ($('#my-select').length > 0) {
    $('#my-select').select2();
}

// Handle method calls on uninitialized elements
try {
    $('#my-select').select2('open');
} catch (error) {
    console.error('Select2 not initialized:', error);
}

// Check for Select2 initialization before calling methods
if ($('#my-select').data('select2')) {
    $('#my-select').select2('data');
}

Install with Tessl CLI

npx tessl i tessl/npm-select2

docs

ajax.md

configuration.md

data-management.md

events.md

index.md

initialization.md

theming.md

tile.json