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

583
Vistas
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 Respuestas
Responde la pregunta

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 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