After setting a placeholder for my select2 autocomplete, I noticed that when I move my cursor away from the input field, the placeholder disappears. However, I would like it to always remain visible. Below is the code I am using, and I hope to find a way to fix this issue correctly.
$(function(){
$("#select2-single-box").select2({
placeholder: "Type a country",
templateResult: addUserPic,
templateSelection: addUserPic,
minimumInputLength: 2,
allowClear: true,
}).on('select2:select', function (e) {
$(this).val([]).trigger('change');
$(this).val([e.params.data.id]).trigger("change");
});
function addUserPic(opt) {
if (!opt.id) {
return opt.text;
}
var optimage = $(opt.element).data('image');
if (!optimage) {
return opt.text;
} else {
var $opt = $(
'<span class="userName"><img src="' + optimage + '" class="userPic" /> ' + $(opt.element).text() + '</span>'
);
return $opt;
}
};
});
.select2-results__message{
display:none;
}
.form-group {
padding: 25px;
}
select {
width: 45%;
padding: 12px;
cursor: text;
border: 1px solid #aaa;
}
/* Other CSS rules */
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<div class="form-group">
<select class="form-control" id="select2-single-box" onChange="window.document.location.href=this.options[this.selectedIndex].value;">
<option></option>
<option value="http://www.google.com" data-image="http://icons.iconarchive.com/icons/custom-icon-design/all-country-flag/16/Belgium-Flag-icon.png">Belgium</option>
<!-- More options -->
</select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>