Display HTML Tags in Options in select2

There are many situations in which a developer has to display HTML in the options of a dropdown box. They can be flag images in a country selection or descriptions in a currency selection. 

select2 provides templateResult and escapeMarkup to make this achievable. templateResult allows option displays to be overridden while escapeMarkup allows HTML tags to be processed.

<select class="select2">
<option value="p101" data-desp="Product 101 in another store">Product 101</option>
<option value="p102" data-desp="Unavailable Product">Product 102</option>
<option value="p103" data-desp="Another type">Product 103</option>
<option value="p104" data-desp="Product 104">Product 104</option>
<option value="p105" data-desp="Product 105">Product 105</option>
templateResult: productTemplate,
escapeMarkup: function(m) { return m; }

function productTemplate(state) {
var original = state.element;
var result = '<table cellspacing="0" cellpadding="0" width="100%">';
result += '<tr>';
result += '<td width="60" valign="top" style="color: red;">';
result += state.id;
result += '<td style="color: blue">';
result += $(original).data('desp');
result += '</td>';
result += '</tr>';
result += '</table>';
return result;


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.