× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

A slightly slimmed down version of the official Select2 ajax example on how to have an ajax-powered autocomplete dropdown

Alex Thornton
May 13, 2015
<p>The code has been taken from https://select2.github.io/examples.html and adjusted for simplicity.</p> <pre><code class="language-html">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;script src="//code.jquery.com/jquery-1.11.3.min.js"&gt;&lt;/script&gt; &lt;link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" /&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"&gt;&lt;/script&gt; &lt;title&gt;Quick Select2 Ajax-powered Autocomplete Dropdown&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;The following autocomplete dropdown will list public GitHub repositories by quering the list with your search term.&lt;/p&gt; &lt;select class="js-data-example-ajax" style="width: 300px;"&gt; &lt;option value="" selected="selected"&gt;Search ...&lt;/option&gt; &lt;/select&gt; &lt;script type="text/javascript"&gt; $(".js-data-example-ajax") .select2({ ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data, params) { // parse the results into the format expected by Select2 // since we are using custom formatting functions we do not need to // alter the remote JSON data, except to indicate that infinite // scrolling can be used params.page = params.page || 1; // !IMPORTANT! your every item in data.items has to have an .id property - this is the actual value that Select2 uses // Luckily the source data.items already have one return { results: data.items, pagination: { more: (params.page * 30) &lt; data.total_count } }; }, cache: true }, escapeMarkup: function (markup) { return markup; // let our custom formatter work }, minimumInputLength: 1, templateResult: function(repo) { if (repo.loading) return repo.text; return repo.full_name; }, templateSelection: function(repo) { return repo.full_name || repo.text; } }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p> </p>
comments powered by Disqus