How to avoid form submission?
P粉545218185
P粉545218185 2023-08-21 13:38:16
0
2
516
<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>
P粉545218185
P粉545218185

reply all(2)
P粉463418483

You can use inline events like this onsubmit

<form onsubmit="alert('停止提交'); return false;">

or

<script>
   function toSubmit(){
      alert('我不会提交');
      return false;
   }
</script>

<form onsubmit="return toSubmit();">

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.

P粉399585024

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

<form onsubmit="return mySubmitFunction(event)">
  ...
</form>

script

function mySubmitFunction()
{
  someBug()
  return false;
}

Returning false here will not be executed and the form will be submitted in any way. You should also call preventDefault to prevent the default action of Ajax form submission.

function mySubmitFunction(e) {
  e.preventDefault();
  someBug();
  return false;
}

In this case, even if there is an error, the form will not be submitted!

Alternatively, you can use the try...catch block.

function mySubmit(e) { 
  e.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template