Click here to Skip to main content
14,021,889 members
Click here to Skip to main content
Add your own
alternative version

Stats

25.8K views
1K downloads
18 bookmarked
Posted 24 Jun 2015
Licenced CPOL

Image Combobox/Dropdown in MVC4 Razor

, 24 Jun 2015
Rate this:
Please Sign up or sign in to vote.
Image Combobox in HTML is no longer a pain, thanks to JQuery and CSS

Introduction

In one of my ASP.NET MVC4 projects, there was a requirement to show images in combobox/dropdown.
I searched all over the internet about showing images in combobox, but unfortunately I didn’t find any simple solution. Everyone talks about ddslick, jquery + msdropdown, jquery plugins all those are very complex.
As a programmer, I don't like to buy component for simple things like this, so I decided to build my own image combobox/dropdown.
And I felt this will help other programmers and save their days of research and hence sharing this here, enjoy. :)

Background

HTML dropdown does not support images and if we try to put styling in normal HTML dropdown like below:

<select>
     <option style="background-image:url(images/volvo.png);" value="volvo">Volvo</option>
     <option style="background-image:url(images/saab.png);" value="saab">Saab</option>
     <option style="background-image:url(images/honda.png);" value="honda">Honda</option>
     <option style="background-image:url(images/audi.png);" value="audi">Audi</option>
</select>

The above code will work only on Firefox browser, but not on Internet Explorer and Chrome and hence there was a need to develop custom combobox with image support in HTML that supports all browsers.

Using the Code

Design:

Step 1: Create Div Tag

<div class="customCombobox" id="customCombobox1"></div>

The above code will create normal HTML div tag. Now, let's add styling to our div tag.

.customCombobox {
        width: 120px;
        height: 22px;
        border: 1px solid black;
        background-image: url('../../Images/down.png');
        background-repeat: no-repeat;
        background-position: right;
        margin: 0;
        padding: 0;
        cursor: pointer;
        align-content: center;
    }

After styling, if we run our HTML or cshtml page above div tag will look like the image given below:

We are done with our first step of creating our custom image combobox/dropdown.

Step 2: Create dropdown 'ul' and 'li'

Here, we are going to create our dropdown using unordered HTML list. The novice programmers can refer to this link to know more about unordered HTML list.

Let's create our dropdown unordered list:

<ul class="ulcustomCombobox" id="ulcustomCombobox1">
    <li id="1"><a><img src="~/Images/fb.png" class="imgDisplay" />
       <p class="imageText">Facebook</p></a>
    </li>
    <li id="2"><a><img src="~/Images/twitter.png" class="imgDisplay" />
       <p class="imageText">Twitter</p></a>
    </li>
    <li id="3"><a><img src="~/Images/orkut.png" class="imgDisplay" />
       <p class="imageText">Orkut</p></a>
    </li>
</ul>

The above HTML code snippet will display items required to display in dropdown. You can customize and add table or div tag to display your dropdown item more properly, I used only <img> and <p> tags to display image and image text, i.e. one <img> and <p> for each dropdown item to display.

Now, let's decorate our dropdown list and set border, width, background and margin, this can be done using CSS given below:

.ulcustomCombobox {
    display: none; /*hide dropdown by default*/
    width: 120px;
    background-color: white;
    border: 1px solid black;
    border-top: none;
    margin: 0;
    padding: 0;
    position:absolute;
}
  • display: none will hide our dropdown list by default (we will make visible this dropdown using jquery later).
  • position: absolute: The element is positioned relative to its first positioned (not static) ancestor element.

Now, let's add border to our dropdown list item:

.ulcustomCombobox li {
            border-top: 1px solid gray;
            height: 22px;
        }

The above CSS code will add border to our dropdown list item and set the height to 22px.

Let's give some mouse over effect to our dropdown list item using CSS:

.ulcustomCombobox li:hover{
            background-color:lightblue;
            cursor:pointer;
        }

The above CSS code will change background color of dropdownlist item on mouse over.

Now, we will align image and its text using CSS.

.imgDisplay{
           display:inline;
           vertical-align:middle;
       }

           .imageText{
               display:inline;
               vertical-align:middle;
               padding-left:5px;
           }

The above CSS code will make image and its respective text vertically center.

Now, if we run our HTML page, our dropdown will look like the image given below:

Hmmm, where is our dropdown list?

You remember we hide our dropdown list by default using display: none. ohhhh :)

Now, how to show dropdown list on down arrow click? Well, we will use jquery to do this.

Step 3: Add Jquery to Complete Functionality of Dropdown List

First of all, add reference to jquery file:

<script type="text/javascript" src="~/Scripts/jquery-1.8.2.js"></script>

Now, handle click event of dropdown arrow using jquery code given below:

<script>
    $(document).ready(function () {
        $("#customCombobox1").click(function () {
            //Get ul tag
            var dropDwn = $(this).next();
            //Show Dropdown
            if (dropDwn.is(":visible"))
                dropDwn.hide();
            else
                dropDwn.show();
        })
    });
</script>

The above Jquery code will display dropdown list if dropdown list is hidden and vice versa.

We are purposefully using $(this).parent().prev(); we can use $('#ulcustomCombobox1') but this will slow down the performance especially when there is huge amount of HTML code in our HTML page, hence we are using $(this).parent().prev(); this will give our unordered list(ul tag) reference respective to div tag.

Now, if we run and click on dropdown arrow, our dropdown list will open and will look like the image given below:

Looking nice, isn't it? yehhh :)

Wait, we aren't done with fully functional image dropdown, we need to handle dropdown item click event and set selected item content in div tag.

We will handle dropdown item click event using jquery:

//Dropdown element click
        $("#ulcustomCombobox1 li").click(function () {
            //Get div tag
            var cmbBox = $(this).parent().prev();
            //Set div tag text/image
            cmbBox.html($(this).html());
            //alert selected element id
            alert("Selected Id:" +  $(this).attr("id"));
            //Hide Dropdown
            $(this).parent().hide();
        });

Let's have a look at what we are doing here.

We are getting reference of div tag using -> var cmbBox = $(this).parent().prev();
We set selected items HTML text to div tag using -> cmbBox.html($(this).html());
Display selected items id using alert i.e. -> alert("Selected Id:" + $(this).attr("id")); and
Finally, hide dropdown list using -> $(this).parent().hide();

If we select any item from dropdown list, it will set its content in div tag like image given below:

Only one thing is remaining now. When user clicks outside our dropdown arrow, we should hide our dropdown list if visible, this is normal combobox behaviour, so let's handle this scenario using jquery.

//Hide Dropdown If User click outside
       $(document).on('click', function (e) {
           var element, evt = e ? e : event;
           if (evt.srcElement)
               element = evt.srcElement;
           else if (evt.target)
               element = evt.target;
           //Hide if clicked outside
           if (element.className != "customCombobox") {
               $("ul.ulcustomCombobox").hide();
           }
       });

Here what we are doing is, we are comparing className of clicked element if it is not "customCombobox" class, then we hide our dropdown items.

We hide all visible dropdown (if more than one combobox is present in one HTML page) list using $("ul.ulcustomCombobox").hide();

That's it. We are done. :)

History

  • Version 1.0

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Akki Kumar
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questionsome suggestions for jquery plugin changes Pin
Gary Dryden3-Jul-15 5:29
memberGary Dryden3-Jul-15 5:29 
AnswerRe: some suggestions for jquery plugin changes Pin
Akki Kumar6-Jul-15 19:10
memberAkki Kumar6-Jul-15 19:10 
QuestionI don't see the jquery attachment Pin
Gary Dryden2-Jul-15 1:44
memberGary Dryden2-Jul-15 1:44 
AnswerRe: I don't see the jquery attachment Pin
Akki Kumar2-Jul-15 1:53
memberAkki Kumar2-Jul-15 1:53 
AnswerRe: I don't see the jquery attachment Pin
Akki Kumar2-Jul-15 19:17
memberAkki Kumar2-Jul-15 19:17 
QuestionA sequel? Pin
AbdullaMohammad29-Jun-15 23:54
memberAbdullaMohammad29-Jun-15 23:54 
AnswerRe: A sequel? Pin
Akki Kumar30-Jun-15 19:24
memberAkki Kumar30-Jun-15 19:24 
Questionmake this a jquery plugin Pin
Gary Dryden29-Jun-15 7:42
memberGary Dryden29-Jun-15 7:42 
AnswerRe: make this a jquery plugin Pin
Akki Kumar30-Jun-15 19:23
memberAkki Kumar30-Jun-15 19:23 
AnswerRe: make this a jquery plugin Pin
Akki Kumar1-Jul-15 23:19
memberAkki Kumar1-Jul-15 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190417.4 | Last Updated 24 Jun 2015
Article Copyright 2015 by Akki Kumar
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid