Home > Software design >  preventDefault() function not working, still refreshing page
preventDefault() function not working, still refreshing page

Time:07-17

I'm messing in HTML/JS to better learn how to use forms. For example, with the following piece of code, I'd like the user to enter a number before submitting the form:

<form>
  <input type="number" min=1 max=100 required>
  <input type="submit" id="t>
</form>

However, attaching the submit button with the following event listener that calls preventDefault() does not stop the page from refreshing when I click on the submit button.

document.getElementById("t").addEventListener("submit", function(event) {
  event.preventDefault();
  console.log("test");
});

Note: Even though I'm using the submit button and the submit event, I don't want to send data to a server. Instead, I'm using the it as a form of input validation, so the user has to input a number between 1-100 before the client responds.

I'm not sure what's going wrong with what I have currently. Any help would be appreciated. Thanks!

CodePudding user response:

As described in my comment just change the element your are attaching the event handler to to the <form> element.

document.querySelector("form").addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("Test");
})
<form>
  <input type="number" min=1 max=100 required>
  <input type="submit" value="Submit"/>
</form>

CodePudding user response:

Submit event handler should be on the form.

<form id="form">
  <input type="number" min=1 max=100 required>
  <input type="submit">
</form>
document.getElementById("form").addEventListener("submit", function(event) {
  event.preventDefault();
  console.log("test");
});

  • Related