1
0
mirror of synced 2024-11-23 21:36:09 +03:00
select2/pages/12.programmatic-control/03.methods/docs.md
2017-09-11 14:34:54 -04:00

3.4 KiB

title metadata taxonomy process never_cache_twig
Methods
description
Select2 has several built-in methods that allow programmatic control of the component.
category
docs
twig
true
true

Select2 has several built-in methods that allow programmatic control of the component.

Opening the dropdown

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');

Closing the dropdown

The close method will cause the dropdown menu to close, hiding the selectable options:

$('#mySelect2').select2('close');

Checking if the plugin is initialized

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).

Destroying the Select2 control

The destroy method will remove the Select2 widget from the target element. It will revert back to a standard select control:

$('#mySelect2').select2('destroy');

Examples

<label for="select2-single">Single select</label>

<button class="js-programmatic-set-val button" aria-label="Set Select2 option">
  Set "California"
</button>

<button class="js-programmatic-open button">
  Open
</button>

<button class="js-programmatic-close button">
  Close
</button>

<button class="js-programmatic-destroy button">
  Destroy
</button>

<button class="js-programmatic-init button">
  Re-initialize
</button>
<p>
  <select id="select2-single" class="js-example-programmatic js-states form-control"></select>
</p>

<label for="select2-multi">Multiple select</label>

<button type="button" class="js-programmatic-multi-set-val button" aria-label="Programmatically set Select2 options">
  Set to California and Alabama
</button>

<button type="button" class="js-programmatic-multi-clear button" aria-label="Programmatically clear Select2 options">
  Clear
</button>

<p>
  <select id="select2-multi" class="js-example-programmatic-multi js-states form-control" multiple="multiple"></select>
</p>