Ren Jitsm
Ren Jitsm

Reputation: 447

How can I stop default submission of form using Vanilla JavaScript

I would like to stop default submission using Vanilla JavaScript. I created a sample of little form. But it gets refreshed when I submit the form even though I call the preventDefault() method. When I use input type="button" it works. But not works with input type="submit".

What will be the reason? Can anyone explain me what is the right method and what's wrong with the code?

My code is as follows:

let validation = () => {
  let form = document.querySelector(".form");
  form.addEventListener("submit", (event) => {
    event.preventDefault();
  });
}
<form action="" class="form" method="post" onsubmit="return validation()">
  <input type="text">
  <input type="submit" value="submit">
</form>

Optional Help: Can anyone give me a proper method or any good references on creating forms. Because when I search, I got lots of tutorials where all are says different methods and I really struggle to find out which method is the standard one.

Upvotes: 0

Views: 922

Answers (1)

Adam Khalish
Adam Khalish

Reputation: 156

Try the following changes to your code:

HTML

<form action="" class="form" method="post" onsubmit="validation(event)">
        <input type="text">
        <input type="submit" value="submit">
</form>

Try removing the return keyword and add event parameter.

JavaScript

const validation = event => {
        event.preventDefault();
}

Using the preventDefault() method of event, the form is hopefully not submitted! Hopefully it works for you.

Upvotes: 2

Related Questions