The question is pretty self-explanatory. I don't understand what the return is doing in the following code:
<form onsubmit="return somefunction()">
If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.
The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.
It means that do nothing on submit.
The onsubmit must execute first, as returning false from it stops the form being submitted, and thus the action ever being requested.
You need the return so the true/false gets passed up to the form's submit event (which looks for this and prevents submission if it gets a false).
Lets look at some standard JS:
function testReturn() { return false; }
If you just call that within any other code (be it an onclick handler or in JS elsewhere) it will get back false, but you need to do something with that value.
... testReturn() ...
In that example the return value is coming back, but nothing is happening with it. You're basically saying execute this function, and I don't care what it returns. In contrast if you do this:
... var wasSuccessful = testReturn(); ...
then you've done something with the return value.
The same applies to onclick handlers. If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.
Once you add the return, you're saying that what you're calling should determine if the event (submit) should continue.
This logic applies to many of the onXXXX events in HTML (onclick, onsubmit, onfocus, etc).
An extension to what GenericTypeTea says - Here is a concrete example:
<form onsubmit="return false">
The above form will not submit, whereas...
<form onsubmit="false">
...does nothing, i.e. the form will submit.
Without the return
, onsubmit
doesn't receive a value and the event is executed just like without any handler at all.
Returning false
from the function will stop the event continuing. I.e. it will stop the form submitting.
i.e.
function someFunction()
{
if (allow) // For example, checking that a field isn't empty
{
return true; // Allow the form to submit
}
else
{
return false; // Stop the form submitting
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With