简体   繁体   中英

preventDefault() function not working, still refreshing page

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!

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>

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM