Add client-side onchange handler to ASP.NET CheckBox control

The ASP.NET CheckBox control offers a convenient abstraction on top of the standard HTML input type="checkbox" control, by marrying a checkbox with a label. Ordinarily, the ASP.NET checkbox works just fine, but if you wanted to have a client-side javascript function triggered when the checkbox is toggled, there is no built-in mechanism to do that.

The usual things to try when one wants to add client-side functionality to ASP.NET controls won't work because the CheckBox control wraps the checkbox input control and the label inside of a span. So, if one were to just add an "onchange" or "onclick" handler either in the markup or in code (via <control>.Attributes.Add("onclick", "blah") call) won't work as these handlers will be attached to the surrounding span.

So what can one do? This will work:

myCheckBox.Attributes.Add("onclick", "foo('" + myCheckBox.ClientID + "');");

What we are doing is adding an onclick handler to the span (which will be processed), and setting it to execute a javascript function foo, passing the client ID of the CheckBox control as the sole parameters. Our foo function may look like this:

<script type="text/ecmascript">
function foo(checkBoxId) {
  var checkBox = document.getElementById(checkBoxId);
  // do something with the checkbox
  // ...

Is this elegant? No!
Is this a leaky abstraction? You better believe it!
Does it work? Yes!