How to prevent form from being submitted?

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

    The following works as of now (tested in chrome and firefox):

    <form onsubmit="event.preventDefault(); return validateMyForm();">
    

    where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

    0 讨论(0)
  • 2020-11-21 07:44

    Here my answer :

    <form onsubmit="event.preventDefault();searchOrder(event);">
    ...
    </form>
    <script>
    const searchOrder = e => {
        e.preventDefault();
        const name = e.target.name.value;
        renderSearching();
    
        return false;
    }
    </script>
    

    I add event.preventDefault(); on onsubmit and it works.

    0 讨论(0)
  • 2020-11-21 07:46

    For prevent form from submittion you only need to do this.

    <form onsubmit="event.preventDefault()">
        .....
    </form>
    

    By using above code this will prevent your form submittion.

    0 讨论(0)
  • 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.');
    });
    <form>
      <button type="submit">Submit</button>
    </form>

    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 .

    0 讨论(0)
提交回复
热议问题