0

I have a Select2 control working with AJAX - I can search a remote repository and select options from it just fine. What I want to do though is add a new option to the control every time the AJAX search comes back to add that search term as a new option.

It shouldn't just add it when the search comes back empty, but with every search.

Ex: I search for baseball and my AJAX search returns the following results:

baseball fields
baseball games
baseball equipment

I want the Select2 dropdown to display:

baseball fields
baseball games
baseball equipment
baseball (Add As New)

Hoping this is as easy as just finding the correct Select2 option to hook into. I can easily append an option in the processResults section of the ajax option, but can't figure out how to grab the actual term that was searched for.

EDIT: This problem is solvable in versions 3.5.2 and below, but I'm using 4.0.

Nick F
  • 72
  • 1
  • 6

1 Answers1

0

I'll answer my own question with a sloppy hack that solves the problem for now... It seems this is easily solvable in Select2 3.5.x with the createSearchChoice option, but that was removed or restructured in v4.0 apparently.

In the ajax option, I was already using url, so I simply declared a global variable lastSearch that I updated before that url was returned

ajax: {
    url: function(params) {
        lastSearch = params.term;
        return "http://myapiurl.com/path/to/endpoint?search=" + params.term;
    }
}

Then in processResults, a quick check to see if the search term was empty, then simply append it to the data returned by my API

processResults: function(data) {
    if (lastSearch != "") {
        data.push({
            id: "-1",
            text: lastSearch + " (Add As New)"
        });
    }
    return { results: data }
}

Again, not the cleanest, but it gets the job done for now. I assume that since this functionality was available in older versions of Select2, it's just been moved somewhere else in v4.0, yet to be found.

Nick F
  • 72
  • 1
  • 6