[removed] does onsubmit only execute when it detects a “return false”

后端 未结 2 1655
难免孤独
难免孤独 2021-01-06 15:32

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 <

相关标签:
2条回答
  • 2021-01-06 15:46

    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.

    0 讨论(0)
  • 2021-01-06 15:54

    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.

    0 讨论(0)
提交回复
热议问题