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 behaviour. 

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.

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

<!DOCTYPE html>
    <title> Image drop down selection </title>
    <link rel="stylesheet" href="" />
<!-- content -->
    <select id="id_select2_example" style="width: 200px;">
        <option data-img_src="">Python programming</option>
        <option data-img_src="">Java programming</option>
        <option data-img_src="">C programming</option>
<!-- /content -->
<!-- scripts -->
<script src=""></script>
<script src=""></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,
    $('.select2-container--default .select2-selection--single').css({'height': '220px'});


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

See you in the nex article, share your thoughts in comments below.



Support Me on Patreon