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.

<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>
$('.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;
    
}

Leave a Comment

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

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. 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.

Close