Saturday, March 24, 2012

Invoking javascript routine on dropdown change

I'm trying to implement a ASP.NET 2.0/Ajax page where a client-side javascript routine is invoked when the user changes the value of a dropdown list. The dropdown list is populated in the Page_Load event.

In the aspx file, I declare the drop down as:

<asp:DropDownList ID="cbIDs" runat="server"OnSelectedIndexChanged="idChanged()" >

Visual Studio complains about "'idChanged' is not a member' of the page.

I've tried searching Google and ASP.Net but haven't been able to find an example on how to do this. Can someone please help me out?

Thanks,

Richard

onselectedindexchanged is a server side event. That is not the right place to hook in client-side code.

Doing the searchhttp://www.google.com/search?q=asp.net+dropdownlist+javascript

brings me the first article at: http://weblog.vb-tech.com/nick/archive/2005/03/25/607.aspx

which shows how to add the onchange attribute to your drop down list. There you can hook in a client side event. Be careful to make sure you fire both client-side and server-side events if you need to.

--JJ


richardr:

OnSelectedIndexChanged="idChanged()" >

richardr:

Visual Studio complains about "'idChanged' is not a member' of the page.

OnSelectedIndexChanged is a server side event... so compiler would try to findidChanged()handler in code behind which is not there..

you need to useOnChange event instead of OnSelectedIndexChanged.


a sample code below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function idChanged()
{
alert("on change event...");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server"onchange="idChanged()">
<asp:ListItem Text="1" Value="1" />
<asp:ListItem Text="2" Value="2" />
<asp:ListItem Text="3" Value="3" />
<asp:ListItem Text="4" Value="4" />
<asp:ListItem Text="5" Value="5" />
</asp:DropDownList>
</div>
</form>
</body>
</html>

No comments:

Post a Comment