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>
2
  • how checked code not working, did you try return false; at bottom in submit callback function. Commented May 26, 2015 at 9:43
  • Thanks. I tried. It's not workable. Commented May 26, 2015 at 9:47

2 Answers 2

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"); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Based on the keyword provided, I found one same question on SO.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.