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

179
Visualizações
How to stop form submission?

I'm new to JavaScript. I need to prevent the form from submitting if any of the validation conditions returned false.

ex:-

if((document.getElementById("name").value)==""){
    alert("'Name' field can not be empty");
    return false;
}

I tried <form onsubmit="return validate();"> and <form onsubmit="event.preventDefault(); validate();">. None of those helped. First one prompt the same alert message twice. Second one continuously prompt all alert messages. What I want is,

  1. If there is one false condition, I need the browser to stop the form from submitting and prompt the relevant alert message.
  2. If there are more than one false conditions, I need the browser to stop the form from submitting and only prompt one alert message.

Is there any way to accomplish this by using JavaScript (No JavaScript libraries)?

Sorry if there are any grammar mistakes, English is not my first language :(

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to call preventDefault of the event object that comes as a parameter you get from the callback function of the EventListener. Like that:

...
<head>
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",function(e)
     {e.preventDefault();});}
</script>
</head>
<body>
<form id="form">
  <input type="submit">
</form>
</body>
...

You can call that parameter anything, and you can also define that function somewhere else.

...
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",handleSubmit);}
function handleSubmit(event)
  {event.preventDefault();}
</script>
...
about 4 years ago · Juan Pablo Isaza 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