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?

Sofyan Setiawan
  • 347
  • 1
  • 6
  • 15

3 Answers3

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

Hope that helps ;)

SiamKreative
  • 126
  • 1
  • 1
  • 9
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;
}
harisrozak
  • 101
  • 4
  • 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/](http://jsfiddle.net/qCn6p/194/) – WildWing Jan 31 '17 at 13:54
  • Hi @WildWing, i have created new fiddle with select2 v4, please check: http://jsfiddle.net/harisrozak/exad6124/ – harisrozak Feb 09 '17 at 08:07
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/

user2030404
  • 86
  • 1
  • 4