2

The problem I encountered is that I have no idea why the submit event cannot be caputred if the form is submitted via Javascript.

Code:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <form id="formA">
        <input type="text" id="name" value="test"/>
        <input type="button" id="btn" value="submit by js"/>
        <input type="submit" id="btn2" value="submit directly"/> <!-- event can be triggered -->
    </form>
</body>
<script type="text/javascript">
    document.getElementById("formA").addEventListener("submit", function() {
        console.log("form is submitted"); // no effect if submitting by js. WHY?
    });
    document.getElementById("btn").addEventListener("click", function() {
        document.getElementById("formA").submit();
    });
</script>
</html>
Howard Wang
  • 601
  • 3
  • 18

2 Answers2

2

I believe this is the correct answer:

It is the expected behavior of the form:

The submit method does not invoke the onsubmit event handler.

Reference: Microsoft - Event handler parameters

In other words, when the form is submitted programmatically the onsubmit event will not trigger. It's only triggered when the submit button is clicked. And this is what I observed when I tested OP's code.

OP also outputs a message to the console to test if the form has been submitted. However, console persistence would need to be enabled to see this message. If not enabled, the console log will get cleared when the form is submitted (making it appear that no message was printed).

document.getElementById("formA").addEventListener("submit", function() {
    console.log("form is submitted"); 
});
Yogi
  • 6,241
  • 3
  • 24
  • 30
  • Thank you. Based on the keyword provided, I found [one same question](http://stackoverflow.com/questions/12819357/form-submitted-using-submit-from-a-link-cannot-be-caught-by-onsubmit-handler) on SO. – Howard Wang May 27 '15 at 00:56
1

You can apply trick to capture submit event on button click, when button client you can add click event on submit, it would also work same that you want to achive

  document.getElementById("formA").addEventListener("submit", function() {
    alert("form is submitted"); // no effect if submitting by js. WHY?
  });
  document.getElementById("btn").addEventListener("click", function() {
    document.getElementById("btn2").click();
  });
<form id="formA" name="formA" action="#">
  <input type="text" id="name" value="test" />
  <input type="button" id="btn" value="submit by js" />
  <input type="submit" id="btn2" value="submit directly" />
  <!-- event can be triggered -->
</form>
Girish
  • 11,907
  • 3
  • 34
  • 51