Saturday, 5 September 2015

Embed icons in HTML select list

You can embed icons into HTML select lists by using the ddslick (http://designwithpc.com/plugins/ddslick). Let's see a practical example. Suppose that we develop a database of projects. Every project has a progress field which expresses the current status of a project. A project can be active (represented in the database with 1 and in the front-end as a green icon), stopped (represented in the database with 2 and in the front-end as a red icon) and finished (represented in the database with 3 and in the front-end as a checkmark icon). We want to build the following html select list of progress values:


The html code is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.ddslick.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#progressList').ddslick({ 
        onSelected: function(data) {
            $('#progress').val(data.selectedData.value);
        }
    });
});
</script>
</head>
<body>
<select id="progressList" name="progressList">
    <option value="1" data-imagesrc="images/green.png" data-description="Active project">Green</option>
    <option value="2" data-imagesrc="images/red.png" data-description="Stopped project">Red</option>
    <option value="3" data-imagesrc="images/finished.png" data-description="Completed project">Completed</option>
</select>
<input type="hidden" id="progress" value=""/>
</body>
</html>

As you can see the ddslick plugin adds two extra attributes to the html select list. The first attribute (data-imagesrc) specifies the option icon and the second attribute (data-description) the option description. You have to be careful if you want to post the list's selected value. In this case, you have to use a hidden field and update its value whenever the list's option changes.