Stop form from submitting with function

Acer

New Member
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
 

Acer

New Member
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.
 

chrishirst

Well-Known Member
Staff member
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.
 
Top