Select2 envents don't fire using ajax

Viewed 10

I edited select2 multiselect to have checkboxes as in the example in https://jsfiddle.net/e0cx6df5/13/. The problem is I added the ajax section, everything works fine but I can't unselect elements (nothing happens), and all the events are not firing up. I use Select2 4.0.13 with bootstrap theme and jquery 1.12.4

jQuery(function($) {
    $.fn.select2.amd.require([
    'select2/selection/single',
    'select2/selection/placeholder',
    'select2/selection/allowClear',
    'select2/dropdown',
    'select2/dropdown/search',
    'select2/dropdown/attachBody',
    'select2/utils'
  ], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {

    var SelectionAdapter = Utils.Decorate(
      SingleSelection,
      Placeholder
    );
    
    SelectionAdapter = Utils.Decorate(
      SelectionAdapter,
      AllowClear
    );
          
    const DropdownAdapter = Utils.Decorate(
      Utils.Decorate(
        Dropdown,
        DropdownSearch
      ),
      AttachBody
    );

    const base_element = '#clients-filter-autocomplete2'
    $(base_element).select2({
        theme: 'bootstrap',
        placeholder: 'Select multiple',
        selectionAdapter: SelectionAdapter,
        dropdownAdapter: DropdownAdapter,
        allowClear: true,
        multiple: true,
        templateResult: function (data) {
            if (!data.id) { return data.text; }

            var $res = $('<div></div>');

            $res.text(data.text);
            $res.addClass('wrap');

            return $res;
        },
        templateSelection: function (data) {
            if (!data.id) { return data.text; }
            var selected = ($(base_element).val() || []).length;
            var total = $('option', $(base_element)).length;
            if (total == 1) {
                return data.text
            }
            return "Selected " + selected;
        },
        ajax: {
            url: '/clients/',
            dataType: 'json',
            delay: 250,
            cache: true,
            data: function (params) {
                var query = {
                  query: params.term,
                }
                return query;
            },
            processResults: function (data) {
                let results = [];
    
                if (data.suggestions.length < 1) {
                    return { results: [] };
                }
    
    
                for (let i = 0; i < data.suggestions.length; i++) {
                    const suggestion = data.suggestions[i];

                    results.push({ text: suggestion.value, id: suggestion.id });
                }
    
                return { results: results }
            }
        }
    })

0 Answers
Related