How to Use Select2 with VueJs 2 OR VueJs 3 Without Plugin – VueJs CDN Tutorial

In this article, we will learn how to use multi-select checkboxes inside Select2 with VueJs 2 or VueJs 3 without any extra vue js component or vue js plugins, we will use just jQuery cdn and VueJs cdn. I searched online a lot but couldn’t find solution except complex select2 vue component based solution. If you are in same situation where you do not want to use select2 vuejs component based solution than this article is for you. For this tutorial we are using VueJs 2 Options API, however, you may still use the logic by updating your VueJs Composition API code accordingly.

In this tutorial, we have taken an example of selecting a country and then loading the cities of that country accordingly in the cities select2 dropdown with multi-select checkboxes, after that, you may select specific cities or cities with specific population from the cities select2 dropdown multi-select checkboxes. Meanwhile, you can also see the selected country and its selected cities. You can follow the example and if you find any difficulty, please share in the comment box.

You can also use below code in your Laravel blade template file. This method will be used to use Select2, and VueJs as cdn in Laravel blade template file.

Full complete code with self-descriptive variable names and comments:

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js" defer></script>
</head>

<body>
    <div id="vueApp">
        <select @change="showCities($event)" v-model="selectedCountry" style="margin-right: 50px; width: 200px;">
            <option value="">Please Select Country</option>
            <option value="country1">Country 1</option>
            <option value="country2">Country 2</option>
            <option value="country3">Country 3</option>
        </select>Selected Country:<b> {{ selectedCountry }} </b><br /><br />
        <select id="idCitiesOfCountry" style="margin-right: 50px; width:200px;">
        </select> Cities of <b>{{ selectedCountry }}</b>: <span
            style="margin-left:50px; margin-right:20px; font-weight: bolder;">{{ selectedCities.join(", ") }}</span>
        <br /><br />
    </div>
    <script>
        var vueInstance;
        $(document).ready(function () {
            vmInstance = new Vue({
                el: '#vueApp',
                data: {
                    selectedCountry: "",
                    cities: [
                        { "name": "city1", "country": "country1", "population": "100" },
                        { "name": "city2", "country": "country1", "population": "200" },
                        { "name": "city3", "country": "country1", "population": "300" },
                        { "name": "city4", "country": "country2", "population": "400" },
                        { "name": "city5", "country": "country2", "population": "500" },
                        { "name": "city6", "country": "country2", "population": "600" },
                        { "name": "city7", "country": "country3", "population": "700" },
                        { "name": "city8", "country": "country3", "population": "800" },
                    ],
                    citiesOfCountry: [],
                    selectedCities: []
                },
                methods: {
                    showCities: function (el) {
                        let vi = this;
                        selCountry = el.target.value;
                        let citiesSelect2 = $("#idCitiesOfCountry");

                        // citiesSelect2.find('option').remove().end();

                        citiesSelect2.html("");

                        citiesSelect2.select2({
                        }).on('select2:open', function (e) {
                            // $(".select2-search__field").addClass("you-custom-class-for-text-field"); //uncomment to fix select2 input textbox width 
                        });

                        citiesSelect2.append('<option value="">Please Select Cities</option>');

                        vi.citiesOfCountry = [];
                        vi.selectedCities = [];

                        for (a = 0; a < vi.cities.length; a++) {
                            if (selCountry == vi.cities[a].country) {

                                citiesSelect2.append('<option value="' + vi.cities[a].name + '">' + vi.cities[a].name + ' - Population: ' + vi.cities[a].population + '</option>');
                                vi.citiesOfCountry.push(vi.cities[a]);
                            }
                        }
                        // dropdownParent: $('#popupDivId'), //uncomment if select2 inside popup window
                        citiesSelect2.select2({
                            closeOnSelect: false,
                            allowClear: false,
                            placeholder: "Please Select Cities",
                            dropdownCssClass: "select2DropdownWidth", //any css class for custom styling
                            templateResult: function (item) {
                                if (!item.id) {
                                    return item.text;
                                }

                                var $result;
                                $result = $('<label class="checkbox"><input type="checkbox" ' + vi.optionExists(item.id) + ' id="cityId-' + item.id + '" onchange="updateSelectedCities(this);" value="' + item.id + '" /><label style="vertical-align:top; cursor:pointer;" for="cityId-' + item.id + '">' + item.text + '</label></label>');
                                return $result;
                            }
                        });
                    },
                    // check if city already selected or not
                    optionExists: function (src) {
                        let vi = this;
                        isChecked = "";
                        if ($.inArray(src, vi.selectedCities) !== -1) {
                            return "checked";
                        } else {
                            return "";
                        }
                        return;
                    }
                }
            });
        });

        function updateSelectedCities(src) {
            selectedCityValue = $(src).val();
            if (true == $(src).prop("checked")) {
                // add checked city 
                vmInstance.selectedCities.push(selectedCityValue);
            } else {
                $(src).prop("checked", false);
                // remove unchecked city
                vmInstance.selectedCities.splice($.inArray(selectedCityValue, vmInstance.selectedCities), 1);
            }
        }
    </script>
    <style>
        .select2DropdownWidth {
            width: 200px !important;
        }

        .select2-container {
            width: 200px !important;
            margin-right: 50px;
        }
    </style>
</body>

</html>