通过 JavaScript 提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4484517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:50:51  来源:igfitidea点击:

Submit Form Via JavaScript

javascripthtml

提问by Joshua

I have an html file with a form containing a submit button, and an anchor tag that is outside of the form. Is it possible to "simulate" the submit button from the anchor link?

我有一个 html 文件,其中包含一个表单,其中包含一个提交按钮和一个位于表单之外的锚标记。是否可以从锚链接“模拟”提交按钮?

In other words can a JavaScript function "call" submit for a form on the page?

换句话说,JavaScript 函数可以“调用”提交页面上的表单吗?

回答by Sarfraz

Sure you can use the submit()method to submit a form like this:

当然,您可以使用该submit()方法提交这样的表单:

<a href="#" onclick="document.FormName.submit()">Submit Form</a>

Or

或者

<a href="#" onclick="document.getElementById('formID').submit()">Submit Form</a>

To go unobstrusive, you can do this instead:

为了不引人注目,你可以这样做:

HTML:

HTML:

You can give your link an id:

你可以给你的链接一个 id:

<a href="#" id="link">Submit Form</a>

Javascript:

Javascript:

<script type="text/javascript">
  var link = document.getElementById('link');

  link.onclick = function(){
    document.getElementById('formID').submit();
    return false;
  };
</script>

where formIDis the idof the form.

其中,formIDidform

回答by Damiqib

Something like this might work... (Assuming that you give an id to your submit button.)

像这样的事情可能会起作用......(假设您为提交按钮提供了一个 ID。)

<a href="#" onclick="document.getElementById('theSubmitButton').click();return false;">Submit form</a>