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

576
Visualizações
What is the difference between using onsubmit directly in DOM vs accessing it from JavaScript?

I'm relatively new to JS and my goal is to put focus on the input field if there is an error (after validation) and I realise that if I write onsubmit=validateFunction() directly in the HTML tag for form, (I assume) it refreshes the page and doesn't put the focus on the input field like how I wanted. Comparing this with calling it in JS, for eg, document.getElementById("myForm").onsubmit = validateFunction; I will be able to get it to work like how I wanted it to. I don't understand the difference between the two, why does one (onSubmit in form tag) refreshes the page (or simply does not put focus on the input field) and the other (calling from JS) works like how I wanted it to?

Here is an example for more clarification on the question:-

function validateFunction() {
  const name = document.getElementById("name");
  if (name.length < 5) {
    alert("Not valid!");
    name.focus();
    name.select();
    return false;
  } else {
    return true;
  }
}
<form id="myForm" action="" onsubmit="validateFunction();">
  <label>Name: <input type="text" id="name"></label>
  <button type="submit">Submit</button>
</form>

compared to (works):

<form id="myForm" action="">
  <label>Name: <input type="text" id="name"></label>
  <button type="submit">Submit</button>
</form>

<script type = "text/javascript" >
document.getElementById("myForm").onsubmit = validateFunction;
</script>

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

0

If you are using the onsubmit attribute, you have to return the returned value of the function.

You also should be checking the length of the input's value property, not the input element itself.

function validateFunction() {
  const name = document.getElementById("name");
  if (name.value.length < 5) {
    alert("Not valid!");
    name.focus();
    name.select();
    return false;
  } else {
    return true;
  }
}
<form id="myForm" action="" onsubmit="return validateFunction()">
  <label>Name: <input type="text" id="name"></label>
  <button type="submit">Submit</button>
</form>

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