Add fontawesome icons into select2 V4 dropdown items

拟墨画扇 提交于 2019-12-05 22:35:58

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

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/

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

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

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!