Link to home
Start Free TrialLog in
Avatar of David Megnin
David MegninFlag for United States of America

asked on

JavaScript in OnClientClick breaks ASP.NET Validation

Hi Experts,

I'm trying to ensure that at least one CheckBox is selected.  This checks the CheckBoxes okay, but breaks validation on the whole page. If I remove the CheckBox check validation works fine. With check() the page submits without any validation working.  How can I fix it so validation still works?

<asp:CheckBox ID="ResourceRoom" runat="server" Text="Resource Room" />
<asp:CheckBox ID="Workshop" runat="server" Text="Attend Workshop" />
<asp:CheckBox ID="Training" runat="server" Text="Training" />
<asp:CheckBox ID="GeneralInfo" runat="server" Text="General Information" />
<asp:CheckBox ID="Interview" runat="server" Text="Interview with an Employer" />

<asp:Button ID="Submit" runat="server" Text="Submit"  />

Open in new window

    <script type="text/javascript">
        function check() {
                var Inputs;
                Inputs = document.getElementsByTagName("input");
                for (var n = 0; n < Inputs.length; ++n)
                    if (Inputs[n].type == 'checkbox' && Inputs[n].checked)
                        return true;

                alert('Select at least one checkbox!');
                return false;
        }
    </script>

Open in new window

 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Submit.Attributes.Add("OnClick", "return check(); ")

Open in new window


I tried taking the return out and validation fired, but after the alert the page submitted without any checkboxes checked:
 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Submit.Attributes.Add("OnClick", " check(); ")

Open in new window

Avatar of strickdd
strickdd
Flag of United States of America image

You would probably have an easier time using a custom validator control and writing the client-side and server-side validation functions that way. It is sure to work with the exisiting validation.
Avatar of David Megnin

ASKER

I would if I knew how.  ;-)
Not helpful.  My script to check that at least one checkbox is checked works fine.  The problem is that any JavaScript in the onclick or OnClientClick of the Submit button breaks Validation on the page.  The CheckBox check works fine, but then the page will submit without any of the Validated TextBoxes being filled in.

Page:
function CheckClientSide(source, arguments)
{
var Inputs;
                Inputs = document.getElementsByTagName("input");
                for (var n = 0; n < Inputs.length; ++n)
                    if (Inputs[n].type == 'checkbox' && Inputs[n].checked)
                        arguments.IsValid = true;

                arguments.IsValid = false;
}

<asp:CustomValidator id="CustomValidator1"
           ControlToValidate="ResourceRoom"
           Display="Static"
           ErrorMessage="Check at least one"           ClientValidationFunction="CheckClientSide"
           OnServerValidate="CheckCheckboxCheck"
           runat="server"/>

Server-Side:
void CheckCheckboxCheck(object source, ServerValidateEventArgs args)
 {
    args.IsValid = (ResourceRoom.Checked || Workshop.Checked || Training.Checked || GeneralInfo.Checked || Interview.Checked);
 }
Is the above adding validation to the CheckBoxes?
These are the fields where the validation is being broken:
            <tr>
                <td>
                    First Name:
                </td>
                <td>
                    <asp:TextBox ID="FirstName" runat="server" type="text" onkeypress="return alpha(event,letters)" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                        ControlToValidate="FirstName" ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
                </td>
                <td style="white-space:nowrap;">
                    Last Name:
                </td>
                <td colspan="3">
                    <asp:TextBox ID="LastName" runat="server" type="text" onkeypress="return alpha(event,letters)" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                        ControlToValidate="LastName" ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
                </td>

            </tr>

Open in new window

Yes, the code provided is for the checkboxes. You only have to add one custom validator to the page and it is set to validate all the checkboxes the way i laid it out.
Oh, okay.  I see.  I'll give it a try.
Hmmm, it says the control can not be validated.  What should I do?
Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 


[HttpException (0x80004005): Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated.]
   System.Web.UI.WebControls.BaseValidator.CheckControlValidationProperty(String name, String propertyName) +1779027
   System.Web.UI.WebControls.CustomValidator.ControlPropertiesValid() +35
   System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +36
   System.Web.UI.Control.PreRenderRecursiveInternal() +103
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of David Megnin
David Megnin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is the only solution that worked.