Wednesday, March 4, 2009

Adding javascript events to dropdownlist items

This code applies to all the controls which contains ListItem, Here is a code sample for DropDownList:
XHTML Code

<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
</asp:DropDownList>

C# code

foreach (ListItem item in DropDownList1.Items)
{
item.Attributes.Add("onclick", "itemclick(this);");
}

Javascript code:

function itemclick(obj)
{
alert(obj.text);
alert(obj.value);
}

No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks