How to prevent form from being submitted?

后端 未结 10 2549
挽巷
挽巷 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:48

    Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:

    const element = document.querySelector('form');
    element.addEventListener('submit', event => {
      event.preventDefault();
      // actual logic, e.g. validate the form
      console.log('Form submission cancelled.');
    });

    I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.

    Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick .

提交回复
热议问题