Question

I have a select2 plugin with the <options> formated. I'm adding a fontawesome icon at the right.

The problem is that when I select any item which has the icon, the icon is not displayed in the current item choosed, when the dropdown is closed. How could I solve it? May be is wrong the format function?

Here is a jsfiddle where you can try: http://jsfiddle.net/uAnLJ/18/

JS

$("#mysel").select2({
    width: "100%",
    formatResult: function(referencia) {
        if (!referencia.id) return referencia.text; // optgroup

        if ($(referencia.element).data('active') == "1") {
            return referencia.text + "<i class='fa fa-check-circle'></i>";
        } else {
            return referencia.text;
        }
    }
});

CSS

body {
    padding: 20px;
}

.fa-check-circle{
    float: right;
    position: relative;
    line-height: 20px;
}

HTML

<select id="mysel">
    <optgroup label="First group">
        <option value="0" data-active="1">Hello</option>
        <option value="1" data-active="0">Stack</option>
    </optgroup>
    <optgroup label="Second group">
        <option value="2" data-active="1">Overflow</option>
        <option value="3" data-active="1">Friends</option>
    </optgroup>
</select>
Was it helpful?

Solution

You need to use formatSelection if you want to change the look of the selected element as well:

formatSelection: function (referencia) {
    if ($(referencia.element).data('active') == "1") {
        return referencia.text + "<i class='fa fa-check-circle'></i>";
    } else {
        return referencia.text;
    }
}

Updated fiddle: http://jsfiddle.net/uAnLJ/22/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top