Skip to content Skip to sidebar Skip to footer

Javascript: Does Onsubmit Only Execute When It Detects A "return False"

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? <

Solution 1:

Using 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 complete 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.

Solution 2:

When returning 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.

Post a Comment for "Javascript: Does Onsubmit Only Execute When It Detects A "return False""