How to use Select2 plugin in cakephp 3?


#1

$(“input.country-id”).addClass(‘select2-offscreen’).removeAttr(‘style’);
$(".state-id").select2({
allowClear: true,
ajax: {// instead of writing the function to execute the request we use Select2’s convenient helper
url: function (term, page) {
var country_id=$(“input.country-id”).val();
//console.log(address_root);
var url = address_root + “cities/states.json?fields=id,title&page=” + page + “&title=” + term;
url += “&country_id=”+country_id;
// var url = address_root + “…/cities/states.json?fields=id,title&page=” + page + “&title=” + term+"&country_id=1";
return url;
},
dataType: ‘json’,
cache: true,
results: function (result, page) {
var out = new Array;
$(result.data).each(function (i, element) {
out.push({
‘id’: element.id,
‘text’: element.location_name
});
});
return {
results: out,
// more: (result.pagination.has_next_page == true)
};
}
},
escapeMarkup: function (markup) {
return markup;
},
initSelection: function (element, callback) {

        var id = $(element).val();

        if (id !== "") {
            var url = address_root + "cities.json?fields=id,title";
            if (id.indexOf(' ') === -1) {
                url += "&id=" + id;

            } else {
                $.each(id.split(' '), function (i, val) {
                    url += "&id[]=" + val;
                });
            }
            $.ajax(url, {
                data: '',
                dataType: "json",
                cache: true
            }).done(function (result) {
                var out = new Array;
                 //console.log(result.data);
                $(result.data).each(function (i, element) {
                    out.push({
                        'id': element.id,
                        'text': element.location_name
                    });
                });
                 // console.log(out);
                if (id > 0) {
                    callback(out[0]);
                } else {
                    callback(out);
                }
            });
        }
    }
});