Submit HTML Form using JavaScript

How to Submit HTML Form using JavaScript?

Here you will learn how to submit HTML forms through JavaScript.

2 way to submit HTML Form using JavaScript

Submit the HTML form using “submit()” method

Let’s see how we can submit the following HTML form through JavaScript.

<form action="" id="my_form">
    <input type="text" name="name" placeholder="Enter your name">
    <input type="submit" value="Submit" id="submit_btn">
</form>

1. First, select the HTML form, in the following JavaScript code you can see, we have selected the form through its ID.

// Selecting the form through its ID.
const the_form = document.getElementById("my_form");

2. After selecting the form, call the submit() method to submit the form via JavaScript.

// Selecting the form through its ID.
const the_form = document.getElementById("my_form");

// call the submit() method to submit the form
the_form.submit();

Submit the HTML form using “click()” method

If an HTML form has a submit button like the following form, use the click() method to fire the button’s click event, and then the form will be submitted.

<form action="" id="my_form">
    <input type="text" name="name" placeholder="Enter your name">
    <!-- Form Submit Button -->
    <input type="submit" value="Submit" id="submit_btn">
</form>

Javascript DOM click() method that will fire the click event of the submit button.

// Selecting the submit button through its ID.
const submit_btn = document.getElementById("submit_btn");

// call the click() method to submit the form
submit_btn.click();