select2 v4 with initial selection
How to set a default / initial selection with more complex properties than id and text
by shanabus
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select class="js-select2">
</select>
CSS
.js-select2{
width: 300px;
}
JavaScript
$(".js-select2").select2({
ajax: {
url: "https://api.myjson.com/bins/hxy4d",
delay: 250,
processResults: processData
},
data: processData([{ "Id": "4", "Code": "JKL", "Description": "Juliet Kilo Laugh" }]).results,
minimumInputLength: 1,
escapeMarkup: function (m) { return m; } ,
templateSelection: myCustomTemplate
});
function processData(data) {
var mapdata = $.map(data, function (obj) {
obj.id = obj.Id;
obj.text = '[' + obj.Code + '] ' + obj.Description;
return obj;
});
return { results: mapdata };
}
function myCustomTemplate(item) {
return '<strong>' + item.Code + '</strong> - ' + item.Description;
}