Predefined options for Select2 control using remote data source

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 selected attribute.

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.

Example

You May Also Like

Comments

  1. Thank you very much for this article! It saved A LOT of time. There was a little problem due to my environment (webpack) – importing that script via tag didn’t work so I imported it directly into my project and everything start to work (with micro adjustments).

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.