title: Methods metadata:
description: Select2 has several built-in methods that allow programmatic control of the component.
taxonomy:
category: docs
process:
twig: true
Select2 has several built-in methods that allow programmatic control of the component.
Methods handled directly by Select2 can be invoked by passing the name of the method to .select2(...)
.
The open
method will cause the dropdown menu to open, displaying the selectable options:
$('#mySelect2').select2('open');
The close
method will cause the dropdown menu to close, hiding the selectable options:
$('#mySelect2').select2('close');
To test whether Select2 has been initialized on a particular DOM element, you can check for the select2-hidden-accessible
class:
if ($('#mySelect2').hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
}
See this Stack Overflow answer).
The destroy
method will remove the Select2 widget from the target element. It will revert back to a standard select
control:
$('#mySelect2').select2('destroy');
Multiple select Set to California and Alabama Clear