Pistachio
Pistachio

Reputation: 1652

Select2 4.0 JSON search not working

After many hours, I finally got the json file to load and to display properly, including the flag icons using Select2 4.0, which looking at how simple the code turned out to look is ridiculous.

But now, for some reason the search function isn't working. I cannot search through any options.

Hopefully it's quick and easy and I can punch myself in the head for not spotting it earlier.

HTML:

<select id="country_select" class="form-control"></select>

JS:

<script>
        function formatCountry (country) {
            if (!country.id) { return country.text; }
            var $country = $(
                    '<span><img src="/assets/img/flags/' + country.code.toLowerCase() + '.png" class="flag" /> ' + country.text + '</span>'
            );
            return $country;
        };

        $('#country_select').select2({
            templateResult: formatCountry,
            templateSelection: formatCountry,
            ajax: {
                url: '/assets/json/countries.json',
                dataType: 'json',
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                processResults: function (data, page) {
                    return {
                        results: $.map(data, function(country) {
                            return { id: country.id, code: country.code, text: country.name };
                        })
                    };
                }
            }
        });

    </script>

JSON:

{
"id":53,
"code":"CW",
"name":"Curaçao",
"iso_alpha_3":"CUW",
"iso_numeric":531
},
{
"id":54,
"code":"CX",
"name":"Christmasøya",
"iso_alpha_3":"CXR",
"iso_numeric":162
},
{
"id":55,
"code":"CY",
"name":"Kypros",
"iso_alpha_3":"CYP",
"iso_numeric":196
},

Upvotes: 2

Views: 2044

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41699

Select2 expects that your results will be filtered on the server side, so it doesn't do any matching of its own when working with AJAX.

Given that your JSON is static, I would recommend just pre-loading it using $.ajax and then using the data option instead of ajax to load it into Select2.

Upvotes: 1

Related Questions