i dont quite understand how the onsubmit="return validate()" works.
why do i have to return the function? does this work only when it detects a return false from the statement?
<script type="text/javascript">
function validate() {
if ((document.example2.naming.value == "") || (document.example2.feed.value == "")) {
alert("You must fill in all of the required .fields!");
return false;
}
else {
return true;
}
</script>
<form name="example2" onsubmit="return validate()">
<input type="submit" name="B1" value="Submit">
Using
returnforonsubmitdetermines whether the form actually submits or not (trueorfalse, respectively). This is useful for Javascript when you want to do something specific before allowing the form to submit or not. For example, like the code you provided, the point is to stop the form from submitting if the form isn’t valid – if a certain field is blank. The important part is that you need to includereturnin the onsubmit part, as well as actually returningtrueorfalsein the function you call. This is because the behavior foronsubmitis to always complete unless you returnfalse. So when you do something like:nothing is returned (because of the lack of
return) – so the function is run but that’s it, so the form is submitted. When you addreturn, then the submitting depends on the return value – what’s returned from the function. If you don’t usereturn, it doesn’t matter what thevalidatefunction returns, because the result ofvalidateis not actually returned toonsubmit.