onSubmit returning false is not working

2019-01-14 22:47发布

I'm completely confused ... I'd swear this was working yesterday ... I woke up this morning and all my forms stopped to work in my project.

All the forms have a "onsubmit" to a function that returns false since it's an ajax call, so the form is never sent.

After a lot of tests, I simplified the question to this piece of code:

<html>
<head>
<script type="text/javascript">
 function sub()
 {
  alert ("MIC!");
  return false;
 }
</script> 
</head>
<body>

<form method = "post" id = "form1" onsubmit = "return sub()">
 input: <input type="text" name="input1" >
    <a href="#" onClick="document.getElementById('form1').submit();">button</a> 
</form>

</body>
</html>

I would swear that this works perfectly, but today is nor working :D

Why if I press the button the form is sent ?

I know it's a total newbie question, but I'm stuck

Thank you !

10条回答
迷人小祖宗
2楼-- · 2019-01-14 23:38

Add "return" in all your onsubmit statements in your form tag...e.g. onsubmit="return validate_function()" this way the return false or return true in your validate function is posted as the result to the return command in your onsubmit.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-14 23:40

Check basic syntaxes and structures... then Check your other forms on your page or input boxes with no form... I had the same problem (or similar: pressing enter in the input box would cause the form to send) ...

I copy pasted the samples above and loaded the page. They worked and mine did not, so i tweaked the formatting and even rewrote it.

查看更多
爷的心禁止访问
4楼-- · 2019-01-14 23:42

Browsers do not call the onSubmit event on the form if you call submit() programmatically.

查看更多
小情绪 Triste *
5楼-- · 2019-01-14 23:43

I suspect he wanted to use a form button that was not of the submit type. In this case, you can also use:

 <input type="button" value="Submit" onclick="if( sub()) document.getElementById('form1').submit()">

Another tip I give is to use the name attribute in all forms, as it is much easier to use: document.form1.submit() instead of document.getElementById('form1').submit(). It is crossbrowser and work in all of them. getElementById is great but not necessary for forms.

查看更多
登录 后发表回答