'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.
Solution 1:[1]
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;
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fortunee |
| Solution 2 | Arnav Thorat |
