Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

575
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!