select2 : Display Display HTML Tags in Options

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

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

[html]
<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>
</select>
[/html]
[javascript]
$(‘.select2’).select2({
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;

}
[/javascript]

Leave a Comment

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