I have a select2 with a list of countries with their flag. To display the select, shows the flag and the country, but the selected text does not display the flag.
This is the code:
$("#cmbIdioma").select2({
templateResult: function (idioma) {
var $span = $("<span><img src='https://www.free-country-flags.com/countries/"+idioma.id+"/1/tiny/" + idioma.id + ".png'/> " + idioma.text + "</span>");
return $span;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>
<div>
<select id="cmbIdioma" style="width: 200px;">
<option value="Spain" selected>Spain</option>
<option value="United_Kingdom">United Kingdom</option>
</select>
</div>
Thanks for your time!
The selected result template can be changed using the option templateSelection.
Copying the same template as templateResult
to templateSelection
:
$("#cmbIdioma").select2({
templateResult: function (idioma) {
var $span = $("<span><img src='https://www.free-country-flags.com/countries/"+idioma.id+"/1/tiny/" + idioma.id + ".png'/> " + idioma.text + "</span>");
return $span;
},
templateSelection: function (idioma) {
var $span = $("<span><img src='https://www.free-country-flags.com/countries/"+idioma.id+"/1/tiny/" + idioma.id + ".png'/> " + idioma.text + "</span>");
return $span;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>
<div>
<select id="cmbIdioma" style="width: 200px;">
<option value="Spain" selected>Spain</option>
<option value="United_Kingdom">United Kingdom</option>
</select>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With