Sometime it is required to display images with the text in the dropdown.
Here is the code to display the images in the dropdown.
Create a folder "flags" and place the flag images there.
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Display images in dropdown</title>
<script type="text/javascript">
function SetFlag()
{
var ddlCountry=document.getElementById('ddlCountry');
var iso = ddlCountry.options[ddlCountry.selectedIndex].value;
if (iso.length > 0)
{
document.getElementById('imgFlag').src = "flags/" + iso + ".png";
ddlCountry.options[ddlCountry.selectedIndex].style.backgroundImage = "url(flags/" + iso + ".png" +")";
ddlCountry.options[ddlCountry.selectedIndex].style.backgroundRepeat="no-repeat";
ddlCountry.options[ddlCountry.selectedIndex].style.backgroundPosition="right";
}
else
document.getElementById('imgFlag').src = "flags/pixel.gif";
}
function getDropdownListTextWithImage()
{
var ddlCountry=document.getElementById('ddlCountry');
for(var j = 0, limit1 = ddlCountry.options.length; j < limit1; j++)
{
ddlCountry.options[j].style.backgroundImage = "url(flags/" + ddlCountry.options[j].value + ".png" +")";
ddlCountry.options[j].style.backgroundRepeat="no-repeat";
ddlCountry.options[j].style.backgroundPosition="right";
}
}
</script>
</head>
<body onload="SetFlag();getDropdownListTextWithImage();">
<form id="form1" runat="server">
<div style="background-repeat:no-repeat;background-position:top right">
<asp:DropDownList runat="server" ID="ddlCountry" onchange="SetFlag();" onkeydown="SetFlag();" onkeyup="SetFlag();" TabIndex="4" EnableViewState="false" ValidationGroup="AddComment"
>
<asp:ListItem value="">[Not specified]</asp:ListItem>
<asp:ListItem value="al" >Albania </asp:ListItem>
<asp:ListItem value="dz">Algeria</asp:ListItem>
<asp:ListItem value="ar">Argentina</asp:ListItem>
<asp:ListItem value="am">Armenia</asp:ListItem>
<asp:ListItem value="au">Australia</asp:ListItem>
<asp:ListItem value="at">Austria</asp:ListItem>
</asp:DropDownList>
<asp:Image runat="server" ID="imgFlag" AlternateText="Country flag" Width="16" Height="11" EnableViewState="false" />
</div>
</form>
</body>
</html>
No comments:
Post a Comment