How to insert FontAwesome inside Select2
Asked Answered
I

3

3

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?

Ikeikebana answered 31/1, 2014 at 2:37 Comment(0)
M
8

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
});
Mosquito answered 5/2, 2014 at 3:16 Comment(1)
This is not working. maybe you check fiddle again @MosquitoFlaring
P
4

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;
}
Pend answered 15/7, 2016 at 4:35 Comment(2)
Hi, This works great for select2 v3. Do you know how to get it working using select2 v4 with change they made to templateSelection and templateResults. The icons don't appear after making the update. See the fiddle. http://jsfiddle.net/qCn6p/194/Electrotechnology
Hi @WildWing, i have created new fiddle with select2 v4, please check: jsfiddle.net/harisrozak/exad6124Pend
F
2

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/

Fingertip answered 21/12, 2017 at 17:51 Comment(1)
adding span has solved it and my code now works with fontawesome 5 icons. span is the trick. thanksFlaring

© 2022 - 2024 — McMap. All rights reserved.