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">
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">
Share
Improve this question
edited Sep 16, 2012 at 17:49
A.M.K
16.8k4 gold badges35 silver badges64 bronze badges
asked Sep 16, 2012 at 17:27
user1666411user1666411
3352 gold badges7 silver badges11 bronze badges
1
- Check your assumptions again. – user166390 Commented Sep 16, 2012 at 17:30
2 Answers
Reset to default 13Using return
for onsubmit
determines whether the form actually submits or not (true
or false
, 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 include return
in the onsubmit part, as well as actually returning true
or false
in the function you call. This is because the behavior for onsubmit
is to always plete unless you return false
. So when you do something like:
onsubmit="validate();"
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 add return
, then the submitting depends on the return value - what's returned from the function. If you don't use return
, it doesn't matter what the validate
function returns, because the result of validate
is not actually returned to onsubmit
.
When return
ing false
, you prevent the form
from being submitted. Otherwise, the form would be submitted, even though it may have validation errors, e.g., the feed
value was empty.
On the other hand, if you return true
, the form data will be submitted to the URL defined by the action
attribute.