Skip to content

JavaScript addEventListener submit

  • by

The submit event is only triggered on the <form> element. You can bind the addEventListener to the <form> element. The onsubmit event occurs when a form is submitted.

Form submit by vanilla JavaScript using the addEventListener method

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <form id="myForm" action="https://google.com" method="get">
    First name:
    <input type="text" name="firstname" size="20">
    <br /> Last name:
    <input type="text" name="lastname" size="20"><br />
    <br />
    <button id="submitBtn" type="button" onclick="formSubmit()">Submit</button>
  </form>
  
  <script>
   function formSubmit() {
    document.getElementById("myForm").submit()
  }

  document.getElementById("submitBtn").addEventListener("click", function(event) {
    event.preventDefault()
    document.getElementById("myForm").submit()
  })
</script>
</body>
</html>

Output:

JavaScript addEventListener submit

More examples

<form id="myForm" action="/action_page.php">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

<script>
document.getElementById("myForm").addEventListener("submit", myFunction);

function myFunction() {
    console.log("The form was submitted");
}
</script>

Do comment if you have any doubts or suggestions on this Js submit topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *