0
votes

(GENERAL PROBLEM: Need to display colored icons (squares) in dropdown items. The color is determined dynamically, the shape is always a square. If there are any better solutions let me know)

I need to display icons in a Dropdown, but it's hard to place images there (and you can't put an I-tag inside an Option), so I'm using the workaround of adding Font-Awesome (FA) Unicode images.

I need to add 'fa-square' to each option as below. According to the below its code is

f0c8     -> 

http://fontawesome.io/icon/square/

My Option Value is dynamically generated from an array, I'm appending as follows:

$.each(items, function(i, item) {
    $('#dropdown').append($('<option></option>').val(item.itemID).html('&#xf0c8; ' + itemTitle));
}); 

But no matter what I do Firefox shows the following Hash Image. Things I've tried:

enter image description here

1) Make the Select have the Font-Awesome font family

<select id="dropdown" style="font-family: 'Font-Awesome'">

(This was the suggestion here, https://github.com/FortAwesome/Font-Awesome/issues/996 )

2) Make the Option have the fa class for all options

$('#dropdown').append($('<option class="fa"></option>').val(item.itemID).html('&#xf0c8; ' + itemTitle));

The Font-Awesome CSS is loaded and available in the project. Any thoughts?

1
You should be using font-family: 'FontAwesome' ... also the article to which you link specifically states that the functionality being attempted is impossible within the <select> input method.Robert
Then what is the solution to display multi-colored boxes in a dropdown as I described? Is there any solution?gene b.
You could rely on just using a single-color icon; the article to which you link shows how that might work. If you need multi-colored boxes your best bet is probably to research a <select> alternative that is powered via JavaScript.Robert
Select2 did the trickgene b.

1 Answers

0
votes

I'm now using the Select2 plugin for my dropdowns. I was able to achieve this by using Select2's templateResult / templateSelection formatting methods.

$('#dropdown').select2(
                                    templateResult: format,
                                    templateSelection: format,
                                    escapeMarkup: function (m) {
                                            return m;
                                    }   
                                });

function format(option) {
    var color = $(option.element).attr('data-color');
    return '<i class="fa fa-square" style="color : ' + color + '"></i> ' + option.text;
};

Note the data-color attr that I have on my Option's, this allows retrieval within Select2's formatting reference functions to determine the individual box color.

<option data-color="..."></option>