Search code examples
jqueryajaxtokenizejquery-select2-4

How do I accept a tokenized input into Select2 (i.e. User pasted options) using ajax?


I am using Select2 in a .NET MVC website to allow users to easily search and select items in a form. This currently works fine however my users have asked if they can have a way of pasting a list of items into the box, instead of searching and selecting them one by one.

I have found information about the Select2 tokenizer parameter which allows overloading the default tokenizer with a custom one. However most examples I've found target older versions of Select2 and I am using version 4.0.

How can I allow pasted lists of tokens using ajax to resolve them?


Solution

  • Below is how I have implemented this. Each token that is separated with either a , or ; is searched using the Ajax method already defined and the first result returned is used.

    $("…").select2({
        …
        tokenizer: function (input, s2, callback) {
            var term = input.term;
            if (term.indexOf(',') < 0 && term.indexOf(';') < 0)
                return input; // Exit if no tokens
    
            var parts = term.split(/,|;/);
            for (var i = 0; i < parts.length; i++) {
                var part = parts[i].trim();
                if (part.length > 2) {
                    $.ajax({
                        url: s2.options.ajax.url,
                        dataType: s2.options.ajax.dataType,
                        data: s2.options.ajax.data({ term: part }),
                        async: false, // If async then unable to return unmatched tokens
                        success: function (data) {
                            var pr = s2.options.ajax.processResults(data, { term: part });
                            callback(pr.results[0]);
                            parts.splice(i--, 1);
                        }
                    });
                }
            }
            return { term: parts.join(';') }; // Rejoin unmatched tokens
        },
        …
    });