OnClick vs OnClientClick for an asp:CheckBox?

Stobor picture Stobor · Jul 16, 2009 · Viewed 178.8k times · Source

Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?

For example, this works:

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

and this doesn't (no error):

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

but this works:

<asp:Button runat="server" OnClientClick="alert('Hi');" />

and this doesn't (compile time error):

<asp:Button runat="server" OnClick="alert('hi');" />

(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)

Answer

SolutionYogi picture SolutionYogi · Jul 16, 2009

That is very weird. I checked the CheckBox documentation page which reads

<asp:CheckBox id="CheckBox1" 
     AutoPostBack="True|False"
     Text="Label"
     TextAlign="Right|Left"
     Checked="True|False"
     OnCheckedChanged="OnCheckedChangedMethod"
     runat="server"/>

As you can see, there is no OnClick or OnClientClick attributes defined.

Keeping this in mind, I think this is what is happening.

When you do this,

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:

  <input type="checkbox" OnClick="alert(this.checked);" />

Obviously, a browser can understand 'OnClick' and puts an alert.

And in this scenario

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

Again, ASP.NET won't change the OnClientClick attribute and will render it as

<input type="checkbox" OnClientClick="alert(this.checked);" />

As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.

You can confirm above by looking at the rendered HTML.

And yes, this is not intuitive at all.