Reputation: 356
I want to create a search input field using select2.js 4.0.5. I looked at the select2 example and basically, want to learn by recreating them without using the template result (only return text).
However, I cannot make it work. This is the closest I can get: myJSFiddle.
$(document).ready(function() {
$(".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;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
}
});
});
Even copying directly everything from the example does not work: exampleJSFiddle.
I am still new to JS and Ajax. I'm sure that I'm missing something. Could someone please explain what am I missing?
Upvotes: 0
Views: 6792
Reputation: 356
I finally get it running. Although I don't know how to fix the size of the search box: (Working JSFiddle)
HTML
<select class="js-data-example-ajax"></select>
JS
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
contentType: 'application/json',
dataType: 'json',
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
return {
results: data.items
};
},
cache: false
},
templateResult: formatResult
});
function formatResult(result) {
return result.full_name;
};
Upvotes: 1