Learning While Aging

[JavaScript] Force user to check a box before clicking a button

This has been used a lot on those “sign up” forms. User has to select a check box indicating “I read and agree to the license agreement”, or something like that, before he/she can submit the form. Of course, with ASP.NET, you can let user submit the form and then check the state of the check box in the Button.Click event handler to prompt the user if the check bos is not checked. But my question is “why do you even give them the ability to click the button if they don’t check the box?”

So, I usually add a JavaScript function on the check box to check the state of it. If it is checked, then enable the submit button, otherwise, disable the button.

Here is the JavaScript code (I left out the error checking in the sample code. You should check the type of the controls before you check their properties):

<script language="javascript" type="text/javascript">
    function changeButtonState(boxID, buttonID)
    {
        var chk = document.getElementById(boxID);
        var btn = document.getElementById(buttonID);
        if (chk.checked)
        {
           btn.disabled = false;
        }
        else
        {
           btn.disabled = true;
        }
    }
</script>

How to use it?

In the Page_Load event handler, add this line of code:

 Me.CheckBox1.Attributes.Add("onclick", "changeButtonState('" & Me.CheckBox1.ClientID.ToString() & _
                        "', '" & Me.Button1.ClientID.ToString() & "')")

Here are soem screen shots:

Button is disabled because the check box is not checked