I am using Select2 plug-in extensively in one of the projects. Some of the Select2 controls get data via Ajax. I needed a way to retrieve remote data and give user an ability to select an option from the list of predefined suggestions. For example, imagine a dropdown control on a travel website where you could search for a destination and there is a list of 10 most popular destinations already in the list.
At first I thought I could just add
<option>...</option> tag for each predefined suggestion. This would have been a very natural way to handle it. Unfortunately when Select2 control retrieves data remotely via Ajax, it ignores all
option HTML tags except the placeholder
<option></option> or options with
Unfortunately there is no built-in way to do it. I have found this issue on GitHub discussing the feature I needed. Gladly one of the commenters, Stanislav Govorov, has created a custom adapter that allowed to add predefined options to Select2 control.
There are couple minor issues with the adapter he created, so I forked it and made a few fixes/improvements to handle data format expected by Select2 control by default.
Show predefined options with no selected option
Show predefined options with selected option
Select2 control removes option with
selected attribute from the list. The trick is to list the selected option twice, second time without
selected attribute. This is counter-intuitive but this is how to do it with Select2 and Ajax-sourced data.