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

220
Views
Javascript form onsubmit is not working as expected

Why does the following code not cause foo() to be called?

<script>
    function foo(){
        alert("hi"); 
        return false;
    }; 

    var myForm=document.createElement('FORM'); 
    myForm.method='POST'; 
    myForm.action="http://www.example.com/test.php"; 
    myForm.id="myForm"; 

    myForm.onsubmit="return foo()";

    document.body.appendChild(myForm); 

    document.getElementById("myForm").submit();
</script>

I tried myForm.onsubmit="(e)=>{alert("hi"); e.preventDefault()}"; as well, also not working.

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

The onsubmit should be set to the actual function not a string wrapped in quotes

Consider changing this

myForm.onsubmit="return foo()";

To this

myForm.onsubmit=foo;
about 4 years ago · Santiago Gelvez Report

0

The onsubmit function is supposed to be a function, not a string.

If you set it as a string, it won't work properly.


To fix it, simply set it as a function, as below.

myForm.onsubmit = foo;

Make sure to not add parentheses (otherwise you will be calling it, and it won't work).


You can also try the addEventListener function, like so.

myForm.addEventListener("submit", foo);

It does the same thing as onsubmit, but with a different syntax.

about 4 years ago · Santiago Gelvez 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!