Home  >  Q&A  >  body text

How to avoid form submission?

<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粉545218185P粉545218185397 days ago441

reply all(2)I'll reply

  • P粉463418483

    P粉4634184832023-08-22 12:35:21

    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.

    reply
    0
  • P粉399585024

    P粉3995850242023-08-22 11:25:35

    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;
    }

    reply
    0
  • Cancelreply