Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 draw image and text on selected option

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.

enter image description here

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!

like image 635
Duefectu Avatar asked Dec 17 '22 19:12

Duefectu


1 Answers

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>
like image 129
Shashank Avatar answered Dec 28 '22 11:12

Shashank