- Forms: event and method submit
- Event: submit
- Method: submit
- Tasks
- Modal form
- Comments
- How to Submit a Form with JavaScript – JS Submit Button Example
- How to Create the HTML Form
- How to Submit a Form with JavaScript
- Conclusion
- How to submit a form using JavaScript
- HTML Form Creation
- Access Form and retrieve Values from the form
- Submit Form and Validate Data
- Conclusion
- About the author
- Shehroz Azam
Forms: event and method submit
The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript.
The method form.submit() allows to initiate form sending from JavaScript. We can use it to dynamically create and send our own forms to server.
Let’s see more details of them.
Event: submit
There are two main ways to submit a form:
Both actions lead to submit event on the form. The handler can check the data, and if there are errors, show them and call event.preventDefault() , then the form won’t be sent to the server.
Both actions show alert and the form is not sent anywhere due to return false :
First: Enter in the input field
Second: Click "submit":
When a form is sent using Enter on an input field, a click event triggers on the .
That’s rather funny, because there was no click at all.
Method: submit
To submit a form to the server manually, we can call form.submit() .
Then the submit event is not generated. It is assumed that if the programmer calls form.submit() , then the script already did all related processing.
Sometimes that’s used to manually create and send a form, like this:
let form = document.createElement('form'); form.action = 'https://google.com/search'; form.method = 'GET'; form.innerHTML = ''; // the form must be in the document to submit it document.body.append(form); form.submit();
Tasks
Modal form
Create a function showPrompt(html, callback) that shows a form with the message html , an input field and buttons OK/CANCEL .
- A user should type something into a text field and press Enter or the OK button, then callback(value) is called with the value they entered.
- Otherwise if the user presses Esc or CANCEL, then callback(null) is called.
In both cases that ends the input process and removes the form.
- The form should be in the center of the window.
- The form is modal. In other words, no interaction with the rest of the page is possible until the user closes it.
- When the form is shown, the focus should be inside the for the user.
- Keys Tab / Shift + Tab should shift the focus between form fields, don’t allow it to leave for other page elements.
showPrompt("Enter something
. smart :)", function(value) < alert(value); >);
P.S. The source document has HTML/CSS for the form with fixed positioning, but it’s up to you to make it modal.
A modal window can be implemented using a half-transparent that covers the whole window, like this:
Because the covers everything, it gets all clicks, not the page below it.
Also we can prevent page scroll by setting body.style.overflowY=’hidden’ .
The form should be not in the , but next to it, because we don’t want it to have opacity .
Comments
- If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
- If you can’t understand something in the article – please elaborate.
- To insert few words of code, use the tag, for several lines – wrap them in tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)
How to Submit a Form with JavaScript – JS Submit Button Example
Joel Olawanle
When building applications and websites on the internet, you’ll sometimes need your users to supply information by filling out a form.
But then you might wonder – how do you get this data from the form? Well, you can do this with JavaScript.
In this article, you will learn how to create a form and get data from it when the form is submitted with JavaScript.
This article won’t cover how to input data into a database – it will only cover how to submit a form. But you should know that once you have this data, you can send it to the database of your choice, use it to manipulate information, and much more.
To submit a form using JavaScript, you must first create the form and add distinctive, specific attributes to the input fields. You will use these attributes to retrieve the data when the user submits and then calls a function to handle validations (possibly if any data is submitted).
How to Create the HTML Form
To get started, let’s create a basic HTML form with two fields: username and password. We’ll also add a button that will be used to submit the form and trigger a JavaScript action.
To get this form’s data via JavaScript, you’ll need to attach specific attributes to the form input field and the form itself. These attributes can be an id , a class , or even with the name tag. This will help get the data in JavaScript using their document methods.
For example, if you use an id attribute on your input field, you can access the input field data and other values using the document method getElementByID(‘idName’) :
// HTML // JS let myUsername = document.getElementById('username'); console.log(myUsername);
If you use a class attribute, you’ll use getElementsByClassName(className) , which returns an array of all elements with the className . If it is only one element, you can use the index number 0 to access its data:
// HTML // JS let myUsername = document.getElementsByClassName('username'); console.log(myUsername[0]);
If you use the name attribute, you’ll use getElementsByName(name) . This is similar to how the class attribute works since it also returns an array which you can loop through or access with its index number:
// HTML // JS let myUsername = document.getElementsByName('username'); console.log(myUsername[0]);
Note: This will not return the input value but the input element itself.
How to Submit a Form with JavaScript
The first step is to attach your preferred attribute to the form, which you can use to track when the form is submitted. This can be an id , class or name attribute, but for this article, I will use id for the form and input fields:
At this point, you can now handle form submission with JavaScript. You first get the form with your preferred attribute, which can be an id, and store it in a variable:
let loginForm = document.getElementById("loginForm");
Then you can attach the addEventListener to the form variable and listen for a submit event. This event listener allows you to attach a callback function which gets triggered once the form is submitted:
loginForm.addEventListener("submit", (e) => < e.preventDefault(); // handle submit >);
At this point, you can now get the form data and handle any operation you wish. For this article, let’s first validate the data by checking if the input is empty before performing any operation:
loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < // throw error >else < // perform operation with form input >>);
This is the entire JavaScript code:
let loginForm = document.getElementById("loginForm"); loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < alert("Ensure you input a value in both fields!"); >else < // perform operation with form input alert("This form has been successfully submitted!"); console.log( `This form has a username of $and password of $` ); username.value = ""; password.value = ""; > >);
Conclusion
In this article, you have learned how to submit a form with JavaScript and how it works with the various DOM methods.
There are other ways you can do this, but this is a straightforward way to handle submission in JavaScript.
You can access over 150 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.
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 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:
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:
Submit Form Using JavaScript < / title >
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:
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 == »
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 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.