Click here to Skip to main content
15,867,308 members
Articles / Web Development / HTML

Image Combobox/Dropdown in MVC4 Razor

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
24 Jun 2015CPOL4 min read 43.9K   1.4K   17   10
Image Combobox in HTML is no longer a pain, thanks to JQuery and CSS
Sometimes, there is a requirement to show images in combobox/dropdown. As a programmer, I don't like to buy components for simple things like this, so I decided to build my own image combobox/dropdown which I share with you in this article.

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 components for simple things like this, so I decided to build my own image combobox/dropdown.

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:

HTML
<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

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

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

CSS
.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:

HTML
<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:

CSS
.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:

CSS
.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:

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.

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:

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

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

jquery
<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:

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.

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

  • 24th June, 2015: Version 1.0

License

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


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

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