如果以编程方式发起提交,则提交事件不会触发 [英] submit event does not fire if submit initiated programmatically
问题描述
我有一个带按钮的HTML表单:
I have a HTML form with button:
<form action="/" method="post" id="MyForm">
<input type="hidden" name="Field1" value="Value1" />
<input type="hidden" name="Field2" value="Value2" />
<input type="submit" name="name" value="submit" />
</form>
我将事件处理程序附加到Window:
I have event handler for submit attached to Window:
window.onsubmit = function()
{
alert("Submit happening!");
};
如果我单击提交按钮,此事件处理程序将正确触发。
但是,当通过javascript以编程方式触发提交时,事件将永远无法正常工作:
This event handler fires properly if I click "Submit" button. However events never works when submit is triggered programmatically from javascript:
$("#MyForm")[0].submit();
如何通过Javascript(而不是通过用户单击)启动提交事件处理程序?
我尝试使用Jquery或AddEventListener订阅Form事件-不起作用。
How to catch submit event handler when it was initiated by Javascript, not by User click? I tried to subscribe for Form event using Jquery or AddEventListener - does not work.
推荐答案
那是因为您不应该只需使用 submit
函数,但 trigger
提交即可,例如:
That's because you shouldn't just use the submit
function, but trigger
the submit like:
$("#MyForm").trigger('submit');
这篇关于如果以编程方式发起提交,则提交事件不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!