How to avoid form submission?
P粉545218185
2023-08-21 13:38:16
<p>I have a form with a submit button somewhere in it. </p>
<p>However, I would like to somehow "catch" the commit event and prevent it from happening. </p>
<p>Is there a way to do this? </p>
<p>I cannot modify the submit button because it is part of a custom control. </p>
You can use inline events like this
onsubmit
or
Example
Now, when developing large projects, this is probably not a good idea. You may need to use event listeners.
Please read more about inline events vs event listeners (addEventListener and IE's attachEvent) here . Because I can't explain it better than Chris Baker.
Unlike other answers, returning
false
is only the part of the answer. Consider the case where a JS error occurs before the return statement...html
script
Returning
false here
will not be executed and the form will be submitted in any way. You should also callpreventDefault
to prevent the default action of Ajax form submission.In this case, even if there is an error, the form will not be submitted!
Alternatively, you can use the
try...catch
block.