Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 preloaded tags in Select2 input box

I have a Select2 input that is working great. The user can start typing and select an option from the dropdown menu and it adds a tag into the input field, they can also create their own tags thanks to the createSearchChoice function.

My scenario is when a user types in a customer's name who already exists, it locks on, and I want it to populate the field with tags (usual suppliers). The user can then delete or add more tags if they want.

My code is:

$('#usualSuppliers').select2({
        containerCssClass: 'supplierTags',
        placeholder: "Usual suppliers...",
        minimumInputLength: 2,
        multiple: true,
        placeholder: 'Usual suppliers...',
                createSearchChoice: function(term, data) {
            if ($(data).filter(function() {
                return this.name.localeCompare(term) === 0;
            }).length === 0) {
                return {id: 0, name: term};
            }

        },
        id: function(e) {
            return e.id + ":" + e.name;
        },
        ajax: {
            url: ROOT + 'Ajax',
            dataType: 'json',
            type: 'POST',
            data: function(term, page) {

                return {
                    call: 'Record->supplierHelper',
                    q: term
                };
            },
            results: function(data, page) {
                return {
                    results: data.suppliers
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });

How can I make it pre-populate the input with tags that come in from an Ajax request?

like image 777
imperium2335 Avatar asked Mar 22 '23 13:03

imperium2335


1 Answers

I managed to solve the issue thanks to this post:

Load values in select2 multiselect

By using trigger.

like image 77
imperium2335 Avatar answered Mar 25 '23 08:03

imperium2335