How to insert FontAwesome inside Select2

邮差的信 提交于 2019-12-22 10:45:22

问题


I have no idea how to insert fontawesome inside Select2. What should I add the CSS or JS in it? I have a view like below.

click : http://s10.postimg.org/675fig9vd/Capture121212121.png

Can anyone help me?


回答1:


Based on my plugin WP Mobile Splash Page Editor, I made a quick fiddle: http://jsfiddle.net/SiamKreative/qCn6p/

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

Hope that helps ;)




回答2:


Based on SiamKreative answer, you can also add formatSelection to select2 options so the selected item can have the icon too. Below is detailed code:

JavaScript:

function format(icon) {
    var originalOption = icon.element;
    return '<i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text;
}

$('.wpmse_select2').select2({
    width: "100%",
    formatResult: format,
    formatSelection: format
});

Add this css code to style the selected item:

.select2-chosen .fa {
    float: right;
    position: relative;
    line-height: 26px;
}



回答3:


You need to return a jquery object instead of a string to prevent it being escaped in v4

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

http://jsfiddle.net/dleffler/15myta6t/



来源:https://stackoverflow.com/questions/21471501/how-to-insert-fontawesome-inside-select2

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