1

This form automatically transfers the user to another form. The question i have is that when the script block is placed after the form block the code works. But when I swap them; so that script is above form, then the form doesn't work.

Can anyone tell why?

Works:

<form id="ponyo_form" action="formB.html" method="POST">
    <input type="text" name="id" value="10" />
    <input type="text" name="transfer_email" value="someone@aol.com" />
    </form>

 <script type="text/javascript">
     document.getElementById("ponyo_form").submit();
 </script>

This won't work:

<script type="text/javascript">
     document.getElementById("ponyo_form").submit();
</script>

<form id="ponyo_form" action="formB.html" method="POST">
<input type="text" name="id" value="10" />
<input type="text" name="transfer_email" value="someone@aol.com" />
</form>
Julian
  • 4,396
  • 5
  • 39
  • 51

1 Answers1

4

The reason this doesn't work when you have the code before the form, is that the code is run when as it is parsed along the page. So it is attempting to find a form called ponyo_form, which doesn't yet exist in the DOM.

To fix this, either place it after the form, or wrap it on an onload function.

IE:

window.onload = function()
{
    document.getElementById("ponyo_form").submit();
}
JosephGarrone
  • 4,081
  • 3
  • 38
  • 61
  • 2
    Using `window.onload` in 2014 is not really nice... add more than one script that uses it and bang! `addEventListener` is the way you should go nowadays (`attachEvent` for IE 8 and lower). See http://stackoverflow.com/questions/15564029/adding-to-window-onload-event – kapa Feb 21 '14 at 16:06