Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda