Submit A Form Using Javascript

2019-06-11 03:29发布

问题:

<form action="/?wpmlmethod=offsite&amp;list=2&amp;wpmlformid=" method="post">
...
</form>

I tried:

<script type="text/javascript">document.forms[0].submit();</script>

But it didn't work.

回答1:

You should submit it on some click event, etc, for example:

elem = document.getElementById('button_id');

elem.onclick = function(){
  document.forms[0].submit();
};

Update:

As you said form is already filled, you want to submit it straight away, you can try this instead:

window.onload = function(){
  document.forms[0].submit();
};

Note that forms[0] represents the first form on your page, if there are more than one forms on your page, you will need to specify the correct index for it eg forms[1], forms[2], etc



回答2:

  1. Make sure you call the submit method after the form exists (either by placing the script after the form or using an onload or onready event)
  2. Make sure you do not have a form control (e.g. an input) with the name or id of submit as this will clobber the submit method with a reference to that HTMLElementNode.

That said, you probably shouldn't be loading a page just to instantly submit a form with JS in the first place. You should have already had all the information needed on the server when you built the form. It smells of bad design and can break the back button.