Search code examples
javascriptajaxjquery-select2jquery-select2-4

How to use the default search with Select2 even when using a remote data source?


I can populate the dropdown from the data source, but the search field at the top does not filter the results. If I send an AJAX request to the API which returns the data, then loop over the results, creating an <option> element for each result, and appending it to the parent <select>, then initiate Select2 - it works fine.

$("#athletes").select2({
  ajax: {
    url: myUrl,
    type: "GET",
    dataType: "json",
    processResults: function(data) {
      return { results: data.results };
    }
  }
});

However when using the Select2 inbuilt ajax function, the results are returned, but the search is broken. No matter what is searched, all the results are returned. It seems as though the standard procedure is to add extra query parameters to the request, and then filter the results on the server. Is there a way to populate the dropdown from the source, then use the search feature as if it was a pre-populated <select>.


Solution

  • I ended up solving by adding to the processResults() function. By grabbing the search term that was in the box, you can use JavaScripts filter() to filter the list according to the search term.