Home > Software engineering >  Javascript form onsubmit is not working as expected
Javascript form onsubmit is not working as expected

Time:04-10

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.

CodePudding user response:

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;

CodePudding user response:

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.

  • Related