简体   繁体   中英

submit event does not fire if submit initiated programmatically

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>

I have event handler for submit attached to Window:

window.onsubmit = function()
{
    alert("Submit happening!");
};

This event handler fires properly if I click "Submit" button. However events never works when submit is triggered programmatically from javascript:

$("#MyForm")[0].submit();

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提交:

$("#MyForm").trigger('submit');

Browsers don't fire the form's onsubmit handler when you manually call form.submit() .

jQuery also mimicks used to mimick that (see this "wontfix" "bug" report ).

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM