Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  138] [ 1]  / answers: 1 / hits: 191147  / 15 Years ago, thu, july 16, 2009, 12:00:00

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...)


More From » asp.net

 Answers
44

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.


[#99118] Saturday, July 11, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deving

Total Points: 26
Total Questions: 94
Total Answers: 103

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;