how to add image in select options html ?

how to add image in select options html

we can add animage in select options in html. but, we cannot directly achieve it with the HTML alone. To display the images in the select drop-down we have to use javascript libraries. We can add an image in select options using "select2" jQuery library.

what select2 can provide us ?

  • select2 provides the same functionality as normal html select.
  • select2 has searching and tagging capability which is one of the best features.
  • The most interesting thing is its API. By using the select2 API we can customize its representation or behavior.

We use the select2 API to add achieve our functionality. Select2 API provides us two functions "templateResult" and "templateSelection". We utilize these two functions to create our custom html (i.e images in selection) drop down selection with images.

Example Code:

Let's write code to add an image in select options drop down.

<!DOCTYPE html>
<html>
<head>
    <title> Image drop down selection </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" />
</head>
<body>
<!-- content -->
    <select id="id_select2_example" style="width: 200px;">
        <option data-img_src="https://data.world/api/datadotworld-apps/dataset/python/file/raw/logo.png">Python programming</option>
        <option data-img_src="https://sdtimes.com/wp-content/uploads/2018/09/Java-logo-490x301.jpg">Java programming</option>
        <option data-img_src="https://cmkt-image-prd.global.ssl.fastly.net/0.1.0/ps/783373/1160/772/m1/fpnw/wm0/letter-c-cm-.png?1447712834&s=c2ab07fcddfa8acf10c5a0c40f0578c2">C programming</option>
    </select>
<!-- /content -->
<!-- scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<script type="text/javascript">
    function custom_template(obj){
            var data = $(obj.element).data();
            var text = $(obj.element).text();
            if(data && data['img_src']){
                img_src = data['img_src'];
                template = $("<div><img src=\"" + img_src + "\" style=\"width:100%;height:150px;\"/><p style=\"font-weight: 700;font-size:14pt;text-align:center;\">" + text + "</p></div>");
                return template;
            }
        }
    var options = {
        'templateSelection': custom_template,
        'templateResult': custom_template,
    }
    $('#id_select2_example').select2(options);
    $('.select2-container--default .select2-selection--single').css({'height': '220px'});

</script>
</body>
</html>

In above code we have create a custom template function that returns the customized html dom element. you can see the same code in code pen also by visiting the url https://codepen.io/anjaneyulubatta505/pen/bOvoPL.