Submit A Form Using Javascript

大城市里の小女人 提交于 2019-12-23 05:44:15

问题


<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.



来源:https://stackoverflow.com/questions/2847919/submit-a-form-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!