Mastering Select2: Initialization, AJAX, Events, and Advanced Options

Learn how to integrate the Select2 jQuery plugin by initializing basic and remote-data selects, configuring AJAX options, handling its eleven events, and leveraging common parameters and methods such as multiple selection, value setting, and enable/disable features for richer UI controls.

BiCaiJia Technology Team
BiCaiJia Technology Team
BiCaiJia Technology Team
Mastering Select2: Initialization, AJAX, Events, and Advanced Options

What is Select2?

Select2 is a jQuery‑based replacement for HTML <select> elements that adds searching, remote data loading, and many configurable options.

1. Initialization

Two common ways to initialize the widget:

<select id="s1" style="width:300px">
    <option></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

<input type="hidden" id="s2" style="width:300px">

JavaScript:

$("#s1").select2({
    placeholder: 'Dropdown 1'
});

$("#s2").select2({
    placeholder: 'Dropdown 2',
    query: function (query) {
        var data = {results : []};
        for (var i = 1; i < 5; i++) {
            data.results.push({id : i , text: i + ""});
        }
        query.callback(data);
    }
});

The second method is useful when loading data later via AJAX.

2. AJAX configuration

To let Select2 fetch remote data, set the ajax option:

$("#s2").select2({
    placeholder: 'Dropdown 2',
    minimumInputLength: 1,
    ajax: {
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        quietMillis: 250,
        data: function (term, page) {
            return { q: term };
        },
        results: function (data, page) {
            return { results: data.items };
        }
    },
    formatResult: repoFormatResult,
    formatSelection: repoFormatSelection
});

Helper functions:

function repoFormatResult(repo) {
    return repo.full_name;
}
function repoFormatSelection(repo) {
    return repo.full_name;
}

Key parameters:

minimumInputLength : minimum characters before a query is sent.

ajax : defines the request URL, response type, delay, request data, and result processing.

formatResult and formatSelection : customize how items appear in the dropdown and after selection.

3. Events

Select2 emits eleven events. Examples:

// value changed
$("#s2").on("change", function(e) {
    var changeVal = e.val;
    var addedVal = e.added;
    var removedVal = e.removed;
});

// opening dropdown
$("#s2").on("select2-opening", function() { console.log("opening"); });

// item highlighted
$("#s2").on("select2-highlight", function(e) {
    var highlightedVal = e.val;
    var choiceVal = e.choice;
});

// selecting item
$("#s2").on("select2-selecting", function(e) {
    var selectingVal = e.val;
    var choiceVal = e.choice;
});

// item removed
$("#s2").on("select2-removing", function(e) {
    var removingVal = e.val;
    var choiceVal = e.choice;
});

// after data loaded
$("#s2").on("select2-loaded", function() { });

Other events include select2-close, select2-removed, select2-focus, and select2-blur.

4. Common options and methods

Important options:

multiple : enable or disable multiple selection.

closeOnSelect : whether the dropdown closes after a choice (default true).

initSelection : set the initial selected item(s) once during initialization.

Useful methods: $("#s1").select2("val", 1); – set selected value. $("#s1").select2("val", ""); – clear selection. $("#s1").select2("enable", true); – enable. $("#s1").select2("enable", false); – disable.

5. Retrieving the selected value

Getting the value works like any jQuery input: $("#s1").val(). When multiple is true, the result is an array of selected values.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendpluginjQuerySelect2
BiCaiJia Technology Team
Written by

BiCaiJia Technology Team

BiCaiJia Technology Team

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.