Add fontawesome icons into select2 V4 dropdown items

14k views Asked by At

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/

4

There are 4 answers

1
Dipiks On BEST ANSWER

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
});
0
user2030404 On

FYI if you return a string for the templateSelection/templateResult overridden functions, it will be escaped (unless you also override the escapeMarkup function), however if you return a jquery object it will NOT be escaped.

Some examples also disregard formatting input without and id

if (!icon.id) { return icon.text; }

See this Fiddle http://jsfiddle.net/dleffler/15myta6t/3/

0
Manuel Madeira On

You can wrap the return with $.parseHTML().

Example: return $.parseHTML('<i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text);

0
Stev tuned On

Use the "escapeMarkup" option as follow

$('.icons_select2').select2({
    width: "100%",
    templateSelection: iformat,
    templateResult: iformat,
    escapeMarkup: function(m) {
        return m;
     }
});

http://jsfiddle.net/qCn6p/209/