select option data image flag/image code example

Example 1: how to put an image in a dropdown html

<!--Doesn't work in internet explorer-->

<select name="countries" id="countries" class="icon-menu">
<option value="">Select a Country</option>
<option value="US">USA</option>
<option value="IN">India</option>
</select>


CSS

select.icon-menu option {
background-repeat:no-repeat;
background-position:bottom left;
padding-left:30px;
}
select#countries option[value="US"] {
background-image:url(flags/usa.png);
}
select#countries option[value="IN"] {
background-image:url(flags/india.png);
}

Example 2: add image in select2 dropdown

$(".class").select2({
    templateResult: formatState,
    templateSelection: formatState
});

function formatState (opt) {
    if (!opt.id) {
        return opt.text.toUpperCase();
    } 

    var optimage = $(opt.element).attr('data-image'); 
    console.log(optimage)
    if(!optimage){
       return opt.text.toUpperCase();
    } else {                    
        var $opt = $(
           '<span><img src="' + optimage + '" width="60px" /> ' + opt.text.toUpperCase() + '</span>'
        );
        return $opt;
    }
};