Ajax data source with createTag and allowClear option

Hello,

I am having a little problem, I have one select element that uses select2.The data source is fetched from ajax. All this while, I have also set ‘allowClear’ to be true to that the user can ‘un-select’ the current choice. But I also want it to allow user to enter a new value that is not already inside the populated options. To do that, I let the ‘tags’ option have a value of true. and I also used a ‘createTag’ function.

But I realised that once I do this, the ‘allowClear’ functionality does not work properly. I have to click the ‘X’ button on the right side of the box twice to un-select a value. Which I don’t understand why.

Below is my piece of code:

    $('#company-code').select2({
        tags: true,
        ajax: {
            url: currentUrl + "working_url",
            data: function (params) {
                return {
                    q: params.term, // search term

                };
            },
            dataType: 'json',
            type: "GET",
            processResults: function (data) {
                return {
                    results: $.map(data, function (obj) {
                        return { id: obj.VNDCD, text: obj.VNDCD + "-" + obj.COMNM };
                    })
                };
            }


        },
        placeholder: "",
        selectOnClose: true,
        allowClear: true,
        minimumInputLength: 1,
        templateSelection: formatSelect2Selection,
        createTag: function (params) {
            var term = $.trim(params.term);

            if (term === '') {
                return null;
            }

            return {
                id: term,
                text: term + ' (new tag)'
            };
        }
    });

There are a couple of posts in the “Is this a bug” category that reference the allowClear and selectOnClose options. You might want to post your question there and hope that the Select2 developers look into it. Or, if you feel up to it, you could probably take a look at the Select2 source code on GitHub yourself and see if you can troubleshoot (and fix) the issue.