OnClick vs OnClientClick for an asp:CheckBox?

asp.netJavascriptCheckboxOnclickOnclientclick

asp.net Problem Overview


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

asp.net Solutions


Solution 1 - asp.net

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.

Solution 2 - asp.net

Because they are two different kinds of controls...

You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.

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

renders to

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

and

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

renders to

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

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.

Solution 3 - asp.net

You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.

Solution 4 - asp.net

For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged

Solution 5 - asp.net

I was cleaning up warnings and messages and see that VS does warn about it: Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.

Solution 6 - asp.net

Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

Note: Ensure you don't set AutoEventWireup="false" in page header.

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub

Solution 7 - asp.net

You can do the tag like this:

<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />

The .checked property in the called JavaScript will be correct...the current state of the checkbox:

  function checkchanged(obj) {
      alert(obj.checked)
  }

Solution 8 - asp.net

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

Solution 9 - asp.net

One solution is with JQuery:

$(document).ready(
    function () {
        $('#mycheckboxId').click(function () {
               // here the action or function to call
        });
    }
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStoborView Question on Stackoverflow
Solution 1 - asp.netSolutionYogiView Answer on Stackoverflow
Solution 2 - asp.netdatacopView Answer on Stackoverflow
Solution 3 - asp.netrussauView Answer on Stackoverflow
Solution 4 - asp.netSerj SaganView Answer on Stackoverflow
Solution 5 - asp.netBrianKView Answer on Stackoverflow
Solution 6 - asp.netЯрослав БелобородовView Answer on Stackoverflow
Solution 7 - asp.netAlan SimpsonView Answer on Stackoverflow
Solution 8 - asp.netestinamirView Answer on Stackoverflow
Solution 9 - asp.netPhilippeView Answer on Stackoverflow