Add fontawesome icons into select2 V4 dropdown items

WildWing picture WildWing · Feb 1, 2017 · Viewed 8.9k times · Source

I am trying to display fontawesome icons in the Select2 v4 dropdown items. But the dropdown is displaying the html and not generating the actual icon. This method works with select2 V3 but does not seem to with v4. Any help is appreciated. Thank you

HTML

<div class="select2-wrapper">
    <select class="input icons_select2">
        <option value="fa-dribbble" data-icon="fa-dribbble">Dribbble</option>
        <option value="fa-dropbox" data-icon="fa-dropbox">Dropbox</option>
        <option value="fa-facebook" data-icon="fa-facebook">Facebook</option>
    </select>
</div>

JS

function iformat(icon) {
var originalOption = icon.element;
return '<i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text;
}
$('.icons_select2').select2({
width: "100%",
templateSelection: iformat,
templateResult: iformat
});

See the fiddle for an example: http://jsfiddle.net/qCn6p/206/

Answer

Gille Q. picture Gille Q. · Feb 1, 2017

Here is your updated fiddle

You have to wrap your element inside of jquery like this:

function iformat(icon) {
    var originalOption = icon.element;
    return $('<span><i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text + '</span>');
}
$('.icons_select2').select2({
    width: "100%",
    templateSelection: iformat,
    templateResult: iformat,
    allowHtml: true
});