Select2 Ajax Custom query
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.full.min.js"></script>
<select class="player-select form-control">
</select>
CSS
.player-select {
width: 200px;
}
JavaScript
$(document).ready(function() {
$(".player-select").select2({
tags: true,
ajax: {
url: "https://raw.githubusercontent.com/kshkrao3/JsonFileSample/master/select2resp.json",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term // search term
};
},
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
var resData = [];
data.forEach(function(value) {
if (value.LastName.indexOf(params.term) != -1)
resData.push(value)
})
return {
results: $.map(resData, function(item) {
return {
text: item.LastName,
id: item.Id
}
})
};
},
cache: true
},
minimumInputLength: 1
}).on('select2:select', el => {
console.log('run')
})
});