JavaScript

How to submit a form using JavaScript

JavaScript is a high-level web programming language that is becoming popular day by day. It gives our web pages and web applications the ability to perform certain actions and make them interactive. JavaScript offers forms to web developers that assist developers in collecting data from users and storing that data in a database. When working with numerous apps and websites, form submission is a critical phenomenon.

In this post, we will go through how to submit a form using JavaScript in detail but first, we will see how to create an HTML form.

HTML Form Creation

An HTML form can be created by using the <form> tag that is offered by HTML itself and it takes two attributes:

  • The first is the “action” that contains a URL(which handles the submission of the form process).
  • The second attribute is the “method” that has an HTTP method.

An HTTP method can be of various types and the two most commonly used are:

  • GET (used to get some data from a server)
  • POST (used to write data to the server)

However, we won’t use these two attributes in this post as we are not working with a server.

Let us now write HTML code for form creation:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Submit Form Using JavaScript</title>

</head>

<body>

<form id="myForm">

<!-- Input Fields -->

<input type="text" name="username" id="username" placeholder="Enter your Username">

<input type="password" name="password" id="password" placeholder="Enter your Password">

<!-- when clicked on the below button, the form will be submitted -->

<button type="submit">Submit</button>

</form>

<script src="code.js"></script>

</body>

</html>

In the above code, we created a form and gave the id attribute to the form whose significance we will see in a while. Next, we defined two input fields and then defined a button that has a type of submit. In the end, we placed a script tag and referenced the filename “code.js” that will contain our JavaScript code.

Access Form and retrieve Values from the form

Now that we are done with creating our form, let us access this form from JavaScript and then retrieve the values of username and password that are present inside the form tag. To access the form we will use the id attribute mentioned earlier via the following code:

var myForm = document.getElementById('myForm');

In the same manner, we can also get the values from the input fields using the id attribute given in the HTML form. The only difference is that we will give the value at the end of the getElementById so that we can retrieve the value from the input field and not the element itself:

var username = document.getElementById('username').value;

var password = document.getElementById('password').value;

Submit Form and Validate Data

To submit the form, we will use the event listener which listens for a specified listener continuously. An event is simply an interaction of HTML and JavaScript triggered by a user or browser when the user manipulates a page and this event is handled by the event listener.

var myForm = document.getElementById('myForm');
// Event listener that listens for submit event
myForm.addEventListener("submit", function(e){
    e.preventDefault();
// retrieve values
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;

// validate username and password fields
if(username=='' || password==''){
        alert("Please Fill all required fields");
    }
else{
        alert("Form submission successful");
    }
})

In the above code, first, we get the reference of the form using the id attribute and then initiate an event listener of “submit” on this form. The function specified in the event listener will be invoked once the user clicks on the submit button.

Inside the function, we have performed our validation, that is if the input fields of username or password are empty then we will see a message in the alert box saying Please Fill all required fields otherwise we will get the message of Form submission successful.

Let us check first by clicking on the submit button leaving the two input fields empty:

Let us now fill the two fields and see the output:

Conclusion

Forms are very helpful in gathering data from users and then manipulating or playing with that data in JavaScript. In this post, we took help from an HTML <form> tag to initialize a form and then went on to define two input fields and a button. Next, we accessed the form element inside a javascript file and then retrieved the values of form input fields using the id attribute.

In the end, we answered the question of how to submit a form using JavaScript by initiating an event listener that will listen for the submit event, and whenever a user clicks on the submit button, this event will be fired. We also validated our input fields inside the event listener function.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.