Add fontawesome icons into select2 V4 dropdown items

10,277

Solution 1

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
});

Solution 2

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/

Share:
10,277
WildWing
Author by

WildWing

Updated on June 28, 2022

Comments

  • WildWing
    WildWing about 2 years

    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/

  • huykon225
    huykon225 over 6 years
    How I can add FontAwesome into input search of select2?