Skip to content

Submit form using JavaScript

  • by

To Submit a form using JavaScript you have to Create a function that will get executed when the link is clicked. The function will get the element object using the getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method.

or the UI element which triggers the submit() call.

  1. A button <button>submit</button>
  2. A link <a href="#">submit</a>

Apply the aforementioned techniques in order to add an event listener.

Submit form using JavaScript

A simple example code submits a form with JavaScript by clicking a link.

<!DOCTYPE html>
<html>
<body>

  <form id="form__submit" action="form.php" method="post">
    <label>NAME: </label>
    <input type="text" name="name" /><br />

    <label>CITY: </label>
    <input type="text" name="city" /><br /><br />

    <a href="#" onclick="submitForm()">Submit Here</a>
  </form>

  <script>
    function submitForm() {
      let form = document.getElementById("form__submit");
      form.submit();
    }
  </script>
</body>
</html>

PHP code: “form.php”.

<?php
   $name=$_POST['name'];
   $city=$_POST['city'];
   echo "NAME-SUBMITTED : $name <br>";
   echo "CITY-SUBMITTED: $city";
?>

Output:

Submit form using JavaScript

The best way

The best way is to insert an appropriate input tag:

<input type="submit" value="submit" />

The best JS way

<form id="form-id">
  <button id="your-id">submit</button>
</form>
var form = document.getElementById("form-id");

document.getElementById("your-id").addEventListener("click", function () {
  form.submit();
});

Enclose the latter JavaScript code by an DOMContentLoaded event (choose only load for backward compatibility) if you haven’t already done so:

window.addEventListener("DOMContentLoaded", function () {
  var form = document.... // copy the last code block!
});

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading