如何使用 JavaScript 提交表单?

IT技术 javascript
2021-01-17 16:07:29

我有一个带有 id 的表单,theForm它有以下 div,里面有一个提交按钮:

<div id="placeOrder"
     style="text-align: right; width: 100%; background-color: white;">
    <button type="submit"
            class='input_submit'
            style="margin-right: 15px;"
            onClick="placeOrder()">Place Order
    </button>
</div>

单击时,将placeOrder()调用该函数该函数将上述 div 的 innerHTML 更改为“正在处理...”(因此提交按钮现在消失了)。

上面的代码有效,但是现在的问题是我无法提交表单!我试过把它放在placeOrder()函数中:

document.theForm.submit();

但这不起作用。

我怎样才能让表格提交?

6个回答

name表单属性设置"theForm",您的代码将起作用。

这对某些人来说似乎非常明显,但我有一个名称和 ID 为“提交”的按钮,并document.theForm.submit()报告了一个错误。重命名按钮后,代码运行良好。
2021-04-01 16:07:29
@Jonathan 你的按钮叫什么名字?因为,根据api.jquery.com/submit 表单的子元素不应使用与表单属性冲突的输入名称或 ID。
2021-04-01 16:07:29

您可以使用...

document.getElementById('theForm').submit();

...但不要替换innerHTML. 您可以隐藏表单,然后插入一个处理... span,它将出现在它的位置。

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);
@Imray 您可能希望服务器端代码为您执行此操作。
2021-03-29 16:07:29
你怎么告诉它把表格寄到哪里?例如,就我而言,我希望将内容通过电子邮件发送给我
2021-04-02 16:07:29
@MadhuriPatel 您的提交按钮是否也命名为提交?请参阅答案stackoverflow.com/questions/833032/...
2021-04-02 16:07:29
@CodyBugstein 设置action="/{controller}/{action-method}" method="post"您尝试发布的表单的属性。
2021-04-03 16:07:29
因为我的表单名称是 printoffersForm 并且 id 是相同的。document.getElementById('printoffersForm').submit();但我给了我错误提交不是一个函数
2021-04-06 16:07:29

在我的情况下它完美地工作。

document.getElementById("form1").submit();

此外,您可以在如下函数中使用它:

function formSubmit()
{
    document.getElementById("form1").submit();
}
我还没有尝试过,但它看起来比我提供的要糟糕。谢谢 ;)
2021-03-13 16:07:29
这会从input标签提交表单值吗?
2021-03-20 16:07:29
@ChintanThummar然后你就可以处理表单提交使用的document.getElementById(“form1的”)。=的onsubmit功能(){//你可以使用Ajax代码在这里提交表单//而无需刷新页面}
2021-03-30 16:07:29
@roy 是的,它将从输入标签提交表单值。
2021-04-03 16:07:29
document.forms["name of your form"].submit();

或者

document.getElementById("form id").submit();

你可以尝试任何一个......这肯定会奏效......

我将离开我提交表单的方式,而不使用表单中的name标签:

HTML

<button type="submit" onClick="placeOrder(this.form)">Place Order</button>

JavaScript

function placeOrder(form){
    form.submit();
}