Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate input form with Javascript

Is there something I'm doing wrong that stops the form validating? I can't seem to get it to validate when the checkbox is not clicked.

Your help will be appreciated.

<html>
    <head>
    <script type="text/javascript">

    function validateTerms(){
         valid = true;
        if ( document.application-form.terms.checked == false ){
            alert ( "Please accept the terms" );
            valid = false;
        }
        return valid;
    }   
    </script>
    </head>

    <body>

       <form id="application-form" name="application-form" method="post" action=""><br />
       <p><input type="checkbox" name="terms" value="terms" /><b> I have read the <a href="terms.php">Terms</a> *</b>. </p>

         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit Application" onsubmit="return validateTerms()">
        <input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')">
        </form>
    </body>
    </html>
like image 624
Helen Neely Avatar asked Sep 13 '26 02:09

Helen Neely


1 Answers

Input button doesn't have onsubmit event, use onclick instead. There were also other problems such as bad selection etc. , which are solved. See below

See a working demo here http://jsfiddle.net/ZHfX7/

<html>
    <head>

    </head>

    <body>

       <form id="application-form" name="application-form" method="post" action=""><br />
       <p><input type="checkbox" id="terms" name="terms" value="terms" /><b> I have read the <a href="terms.php">Terms</a> *</b>. </p>

         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit Application" onclick="return validateTerms()">
        <input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')">
        </form>
    </body>
        <script type="text/javascript">

    function validateTerms(){
         valid = true;
        if ( !document.getElementById('terms').checked){
            alert ( "Please accept the terms" );
            valid = false;
        }
        return valid;
    }   
    </script>
    </html>
like image 200
Muhammad Usman Avatar answered Sep 15 '26 15:09

Muhammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!