JavaScript Form

Summary: in this tutorial, you will learn about JavaScript form API: accessing the form, getting values of the elements, validating form data, and submitting the form.

Form basics

To create a form in HTML, you use the <form> element:

<form action="/signup" method="post" id="signup"> 
</form>Code language: HTML, XML (xml)

The <form> element has two important attributes: action and method.

  • The action attribute specifies a URL that will process the form submission. In this example, the action is the /signup URL.
  • The method attribute specifies the HTTP method to submit the form with. Usually, the method is either post or get.

Generally, you use the get method when you want to retrieve data from the server and the post method when you want to change data on the server.

JavaScript uses the HTMLFormElement object to represent a form. The HTMLFormElement has the following properties that correspond to the HTML attributes:

  • action – is the URL that processes the form data. It is equivalent to the action attribute of the <form> element.
  • method – is the HTTP method which is equivalent to the method attribute of the <form> element.

The HTMLFormElement element also provides the following useful methods:

  • submit() – submit the form.
  • reset() – reset the form.

Referencing forms

To reference the <form> element, you can use DOM selecting methods such as getElementById():

const form = document.getElementById('subscribe');Code language: JavaScript (javascript)

An HTML document can have multiple forms. The document.forms property returns a collection of forms (HTMLFormControlsCollection) on the document:

document.formsCode language: JavaScript (javascript)

To reference a form, you use an index. For example, the following statement returns the first form of the HTML document:

document.forms[0]Code language: CSS (css)

Submitting a form

Typically, a form has a submit button. When you click it, the browser sends the form data to the server. To create a submit button, you use <input> or <button> element with the type submit:

<input type="submit" value="Subscribe">Code language: HTML, XML (xml)

Or

<button type="submit">Subscribe</button>Code language: HTML, XML (xml)

If the submit button has focus and you press the Enter key, the browser also submits the form data.

When you submit the form, the submit event is fired before the request is sent to the server. This gives you a chance to validate the form data. If the form data is invalid, you can stop submitting the form.

To attach an event listener to the submit event, you use the addEventListener() method of the form element as follows:

const form  = document.getElementById('signup');

form.addEventListener('submit', (event) => {
    // handle the form data
});Code language: JavaScript (javascript)

To stop the form from being submitted, you call the preventDefault() method of the event object inside the submit event handler like this:

form.addEventListener('submit', (event) => {
    // stop form submission
    event.preventDefault();
});Code language: PHP (php)

Typically, you call the event.preventDefault() method if the form data is invalid. To submit the form in JavaScript, you call the submit() method of the form object:

form.submit();Code language: CSS (css)

Note that the form.submit() does not fire the submit event. Therefore, you should always validate the form before calling this method.

Accessing form fields

To access form fields, you can use DOM methods like getElementsByName(), getElementById(), querySelector(), etc.

Also, you can use the elements property of the form object. The form.elements property stores a collection of the form elements.

JavaScript allows you to access an element by index, id, or name. Suppose that you have the following signup form with two <input> elements:

<form action="signup.html" method="post" id="signup">
	<h1>Sign Up</h1>
	<div class="field">
		<label for="name">Name:</label>
		<input type="text" id="name" name="name" placeholder="Enter your fullname" />
		<small></small>
	</div>
	<div class="field">
		<label for="email">Email:</label>
		<input type="text" id="email" name="email" placeholder="Enter your email address" />
		<small></small>
	</div>
	<button type="submit">Subscribe</button>
</form>
Code language: HTML, XML (xml)

To access the elements of the form, you get the form element first:

const form = document.getElementById('signup');Code language: JavaScript (javascript)

And use index, id, or name to access the element. The following accesses the first form element:

form.elements[0]; // by index
form.elements['name']; // by name
form.elements['name']; // by id (name & id are the same in this case)Code language: JavaScript (javascript)

The following accesses the second input element:

form.elements[1]; // by index
form.elements['email']; //  by name
form.elements['email']; // by idCode language: JavaScript (javascript)

After accessing a form field, you can use the value property to access its value, for example:

const form = document.getElementById('signup');
const name = form.elements['name'];
const email = form.elements['email'];

// getting the element's value
let fullName = name.value;
let emailAddress = email.value;Code language: JavaScript (javascript)

Put it all together: signup form

The following illustrates the HTML document that has a signup form. See the live demo here.

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>JavaScript Form Demo</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="stylesheet" href="css/style.css" />
	</head>
	<body>
		<div class="container">
			<form action="signup.html" method="post" id="signup">
				<h1>Sign Up</h1>
				<div class="field">
					<label for="name">Name:</label>
					<input type="text" id="name" name="name" placeholder="Enter your fullname" />
					<small></small>
				</div>
				<div class="field">
					<label for="email">Email:</label>
					<input type="text" id="email" name="email" placeholder="Enter your email address" />
					<small></small>
				</div>
				<div class="field">
					<button type="submit" class="full">Subscribe</button>
				</div>
			</form>
		</div>
		<script src="js/app.js"></script>
	</body>
</html>
Code language: HTML, XML (xml)

The HTML document references the style.css and app.js files. It uses the <small> element to display an error message in case the <input> element has invalid data.

Submitting the form without providing any information will result in the following error: