Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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!

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Santiago Gelvez Denunciar

0

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

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda