JSFiddle - React, Tailwind, and code Playground
by javad ebrahimi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<p>
<select id="sel2" style="width:500px" class="form-control" autocomplete="off"></select>
</p>
JavaScript
$.fn.select2.amd.require([
'select2/utils', 'select2/data/ajax', 'select2/data/minimumInputLength'
], function(Utils, AjaxAdapter, MinimumInputLength) {
function CustomAjaxAdapter($el, options) {
CustomAjaxAdapter.__super__.constructor.call(this, $el, options);
}
Utils.Extend(CustomAjaxAdapter, AjaxAdapter);
var initialValues = [{
id: 909269,
name: 'qwrap'
}];
CustomAjaxAdapter.prototype.current = function(callback) {
var data = [];
CustomAjaxAdapter.__super__.current.call(this, function(d) {
data = d
});
_.each(initialValues, function(el) {
data.push(el);
})
callback(data);
}
CustomAjaxAdapter.prototype.unselect = function(data) {
initialValues = _.reject(initialValues, function(el) {
return el.id == data.id
});
CustomAjaxAdapter.__super__.unselect.call(this, data);
}
$('#sel2').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json',
delay: 800,
data: function(params) {
return {
q: params.term // search term
,
page: params.page
};
},
processResults: function(data) {
return {
results: data.items
};
}
},
multiple: true,
minimumInputLength: 2,
placeholder: 'Select something...',
dataAdapter: Utils.Decorate(CustomAjaxAdapter, MinimumInputLength),
templateResult: function(item) {
return (item.loading) ? item.text : item.name;
},
templateSelection: function(item) {
return item.name;
}
});
});