Client-Side Javascript Event Handlers for ASP.NET Controls — How??

When developing with ASP.NET server controls such as asp:DropDownList or asp:Textbox that you have declared as runat="server", have you struggled with getting an OnChange or OnBlur event handler to be called? If you just do what you would have done with a plain old <input type="text"> or <select> control, which is to give the control an event attribute like onchange="myHandler()", you end up sad — your Javascript event handler never gets called. So how can you get it to be called?

The trick is to assign the event handler to your control programmatically. Here’s an example of doing this in C# as part of the page load event:

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        // Find the control we care about.
        DropDownList ddlist = (DropDownList)FindControl("id_of_dropdown");

        // Give the control our script as an event handler. Note that you
        // don't have to pass a reference to "this" as an argument; if you
        // don't need it, omit it.
        ddlist.Attributes.Add("onchange", "OnChangeHandler(this)");
    }
</script>

<!-- Page content goes here. -->

<script>

    // This is the implementation of our event handling
    // script that was referenced above.

    function OnChangeHandler(obj)
    {
        // Javascript implementation of event handler goes here.
    }

    <!-- Other event handler scripts could go here -->

</script>

<!-- HTML for page goes here -->

In this example, I used the FindControl() method to find the control by id, and then I added my event handler script as an attribute. Although I passed “this” as an argument to my handler, that isn’t required. It was useful for my implementation because I used the same handler for more than one control. If you want no arguments, include the parentheses with nothing between them. Note that the handler is defined in a<script> tag that does not say runat="server" — you want this script to run on the client once your control’s OnChange event fires due to user interaction.

Advertisements
Tagged with: ,
Posted in ASP.NET
One comment on “Client-Side Javascript Event Handlers for ASP.NET Controls — How??
  1. […] that field exists — hidden — and a little JavaScript copies the Username value into it. My post on how to do client-side event handlers in Javascript shows you the code for doing this kind of […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: