How to prevent form from being submitted?

后端 未结 10 2340
挽巷
挽巷 2020-11-21 07:06

I have a form that has a submit button in it somewhere.

However, I would like to somehow \'catch\' the submit event and prevent it from occurring.

Is there s

10条回答
  •  终归单人心
    2020-11-21 07:33

    Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

    html

    ...

    script

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

    returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

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

    In this case, even with the bug the form won't submit!

    Alternatively, a try...catch block could be used.

    function mySubmit(e) { 
      e.preventDefault(); 
      try {
       someBug();
      } catch (e) {
       throw new Error(e.message);
      }
      return false;
    }
    

提交回复
热议问题