Stop form from submitting with function

Discussion in 'Scripts' started by Acer, Jun 11, 2013.

to remove all ads.
  1. Acer

    Acer New Member

    Messages:
    7
    I am trying to validate a form with Javascript. I have simplified my code as much as possible and the form still submits.

    Here is my HTML code:
    Code:
    <html>
    <head>
    <title>Test Form</title>
    <script>
    function submit(){
    return false;
    }
    </script>
    </head>
    <body>
    <form onsubmit="return submit();" >
    <input type="submit" name="submitbutton" value="Submit Form 1" />
    </form>
    <form onsubmit="return false;" >
    <input type="submit" name="submitbutton" value="Submit Form 2" />
    </form>
    </body>
    </html>
    The first form submits, but the second one doesn't. :confused:
    You can find the page at: http://www.avidity.zzl.org/test.html
     
  2. Acer

    Acer New Member

    Messages:
    7
    I've decided to take out the form element and instead add the event to the button:

    Code:
    <html>
    <head>
    <title>Test Form</title>
    <script>
    function submit(){
    alert('validating');
    alert(document.getElementsByName('test')[0].value);
    }
    </script>
    </head>
    <body>
    <input type="button" value="Submit Form" onclick="submit()"/>
    <input type="text" name="test" />
    </body>
    </html>
    Now it works fine. :D Though I'm still confused why the browser doesn't let you use a function for form validation.
     
  3. chrishirst

    chrishirst Well-Known Member Staff Member

    Messages:
    2,611
    because your script does not return false, so the event from the submit button will 'bubble up' to the form handler AS WELL as your event handler.
     

Share This Page