I have a C/C++ programming background, and while casually learning Javascript through the @3C webpages on JS, I found this piece of code –
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
Well, I do not know if I have missed out any of their previous lessons; am confused over the “return” used in the line –
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
My question – Since the “onsubmit” in the above line on calling the function “validateForm()” will anyways be looking for a return value of true/false, what is the significance of this explicit return keyword? I see that on deleting the return keyword, and running the above code (as – onsubmit = "validateForm();" ) works, but even if an error in input is there the form ultimately gets submitted after displaying the warning message.
Could you please throw some light on the use of this “return” keyword in this scenario?
Also, I find that there is a lot of deviation in the way Javascript is written, considering my background in c/c++.. am i alone here..? 🙂
thanks!
I believe everyone has nearly answered the question, but then in different ways. Thanks guys.
I happened to read an excellent article online, which beautifully explains what is actually happening, mostly behind the scenes, using an example that closely resembles the question that I had posted.
Felt this would turn useful for anyone who might face this issue in the future.
Link to the article-
http://www.quirksmode.org/js/events_early.htmlRead the “Prevent Default” section of the page.
–arun nair