Shoora
1/23/2013 - 4:24 PM

Select2 ajax example with custom query call to append data to the request. Note: Providing ajax settings is not needed (and not used) when

Select2 ajax example with custom query call to append data to the request.

Note: Providing ajax settings is not needed (and not used) when query is provided. Left here as a full example.

$("[data-provide='select2']").each(function () {
    var $element = $(this);

    $element.select2({
        placeholder: $element.data("placeholder"),
        minimumInputLength: 0,
        allowClear: true,
        initSelection: function (element, callback) {
            callback({
                id: $(element).val(),
                text: $(element).data('selected-text')
            });
        },
        query: function (query) {
            var url = $element.data("url");

            var contextData = {};
            var contexts = $element.data("context").split(",");
            _.map(contexts, function (c) {
                var name = c.trim();
                var value = $("[name='" + name + "']").val();

                if (value) {
                    contextData[name] = value;
                }
            });

            var data = {
                query: query.term,
                page: query.page,
                pageLimit: 25
            };

            $.extend(data, contextData);

            $.post(url, data, function (results) {
                query.callback(results);
            });

        },
        ajax: {
            url: $element.data("url"),
            type: "POST",
            quietMillis: 100,
            data: function (term, page) {
                return {
                    query: term,
                    page: page,
                    pageLimit: 25
                };
            },
            results: function (data, page) {
                return data;
            }
        }
    });
});