views:

421

answers:

4

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 !

A: 

Try to change you "button" code like that

<a href="#" onClick="return document.getElementById('form1').onsubmit();">button</a> 
Olegas
A: 

The onsubmit event only fires for normal form submissions. It does not fire when the JavaScript submit() method is called.

The best solution is to use a normal submit button here.

If you want to continue with using a link to the top of the page (which isn't unobtrusive, progressive, or graceful) then you need to call the sub() function explicitly and test its return value before deciding if you should call submit() or not.

David Dorward
A: 

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

Andy Shellam
Andy ... I swear you that was working yesterday :)I have a whole project with those kind of structures, and the form was never submitted ...It has to be other thing ... :P
StuckOnSubmit
The submit event would not fire with this code. THREE separate answers all say that! Either you are wrong, or your test case doesn't sufficiently represent your actual code.
David Dorward
Are you sure you didn't have an actual submit button? As that would then work. Perhaps you changed your submit buttons for anchors as an enhancement yesterday? Do you have a source control system? Are other developers also working on the project that could have changed it?
Andy Shellam
A: 

It seems that the 'submit()' function bypasses the 'form' tags 'onsubmit' event in Firefox and IE8. If you use a submit button, then it works as expected:

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

<form method = "post" action="http://google.com" id = "form1" onsubmit = "return sub();">
 input: <input type="text" name="input1" >
     <input type="submit">
</form>

</body>
</html>