Published Jun 01,2019 by Kailash Singh
Show Image in Dropdown list with jQuery

In this tutorial, we are creating a show image in dropdown list with select2 plugins in JQuery.

 

Step 1 :- Add links in your code.

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>  

 

Step 2 :-  Add HTML code on page.

 

<select id='social_icon' style='width: 200px;'>
	<option value=''>---Select Icon---</option>
	<option value='vimeo'>Vimeo</option>
	<option value='facebook'>Facebook</option>
	<option value='linkedin'>Linkedin</option>
	<option value='google_plus'>Google Plus</option>
	<option value='twitter'>Twitter</option>
</select>

 

Step 3 :-  Add JavaScript code on page.

 

 <script>
    $(document).ready(function(){
        $("#social_icon").select2({
             templateResult: formatOptions
        });
    });
        
    function formatOptions (state) 
    {
       if (!state.id) { return state.text; }

       console.log(state.element.value);

       <!-- here i am creating a route of the images folder -->

       var $state = $(
            '<span ><img sytle="display: inline-block;" src="images/' + state.element.value.toLowerCase() + '.png"  /> ' + state.text + '</span>'
            );

        return $state;
    }
</script>

 

Step 4 :-  Create a images folder and you have to store images there.

 

 

Hope this will help our developers.

Because we believe Mantra means CodingMantra

Be First to Comment

Leave a Reply