No effect on trigger change when using ajax data


I’m trying to programmatically change a value from a select2 that uses remote data but it has no effect, the value is not changed.

You call test it as well at the official docs link:

The code i use is the one bellow:


the value ‘39840932’ represents the google/googletest option from the select.

One thing I noticed that this code above works only if you follow the steps:

  1. manually select the google/googletest option from the select
  2. manually change for any other option
  3. run the code above

Looks like it needs the data to come from the server and then you can programmatically change its value, but it should not be this way

The way the Select2 AJAX feature works, it does not load any data into the Select2 until the user types something in the input field. That is what prompts Select2 to query the data source via AJAX. So it is working as designed.

Keep in mind that the purpose of the AJAX feature is to retrieve a subset of a large data set by matching the query term the user has entered. I don’t know how much data is in your data set, but if it’s relatively small and you’re only using the AJAX feature because you want to load the data remotely—and not because you need to do server-side filtering of the data before delivering it to Select2—then you should retrieve the data from the server yourself (for example, using jQuery’s $.json() method), and then use that value as the data property of the Select2 configuration object when you initialize your Select2 widget.