JavaScript Forms in the DOM
Forms are fundamental components of web applications, enabling user interaction and data collection. Learn how to access form elements.
Forms are fundamental components of web applications, enabling user interaction and data collection. This guide covers the practical DOM skills you need to work with them: accessing form and input elements, reading and writing field values, collecting all data at once with FormData, reacting to form events, and validating user input before submission.
If you are new to the DOM, start with Selecting DOM Elements and Introduction to Browser Events, then come back here.
Accessing Form Elements
Selecting Form Elements
You can reach form elements with the same DOM methods you use for any node: getElementById, getElementsByName, getElementsByTagName, and querySelector / querySelectorAll. For most cases prefer getElementById (fastest, when you control the markup) or querySelector (most flexible, supports any CSS selector).
<!DOCTYPE html>
<html>
<head>
<title>Selecting Form Elements</title>
</head>
<body>
<h4>Fill the form inputs, and press 'Show Input Values' button.</h4>
<form id="userForm">
<input type="text" id="username" name="username" placeholder="Username" />
<input type="email" id="email" name="email" placeholder="Email" />
</form>
<button id="showInputs">Show Input Values</button>
<script>
// Select elements by ID
const username = document.getElementById('username');
const email = document.getElementById('email');
const showInputsButton = document.getElementById('showInputs');
// Using querySelector for selection
const emailByQuery = document.querySelector('#email');
showInputsButton.addEventListener('click', () => {
alert(`Username: ${username.value}, Email: ${emailByQuery.value}`);
});
</script>
</body>
</html>This example demonstrates selecting form elements using various methods and displaying their values in an alert when the "Show Input Values" button is clicked.
Using the document.forms Collection
Every form on a page is also available through the built-in document.forms collection, and each named field inside a form is reachable as a property of that form. This is often the most concise way to read values without calling getElementById for each field.
// <form name="userForm">
// <input name="username">
// <input name="email">
// </form>
const form = document.forms.userForm; // or document.forms[0]
console.log(form.username.value); // value of the username field
console.log(form.elements['email'].value); // same via the elements collectionThe form.elements collection contains every control (inputs, selects, textareas, buttons) belonging to the form, indexed by both position and name. See Form Properties and Methods for the full list.
Getting and Setting Input Values
Accessing and Modifying Input Values
Input values can be accessed and modified using the value property.
<!DOCTYPE html>
<html>
<head>
<title>Getting and Setting Input Values</title>
</head>
<body>
<form id="userForm">
<input type="text" id="username" name="username" placeholder="Username" />
<input type="email" id="email" name="email" placeholder="Email" />
<button type="button" id="showValues">Show Values</button>
<button type="button" id="setValues">Set New Values</button>
</form>
<script>
const username = document.getElementById('username');
const email = document.getElementById('email');
const showValuesButton = document.getElementById('showValues');
const setValuesButton = document.getElementById('setValues');
showValuesButton.addEventListener('click', () => {
alert(`Username: ${username.value}\nEmail: ${email.value}`);
});
setValuesButton.addEventListener('click', () => {
username.value = 'newUsername';
email.value = '[email protected]';
alert('Values have been set to new values.');
});
</script>
</body>
</html>This example shows how to get and set the values of input fields. Clicking "Show Values" displays the current input values, and "Set New Values" changes them and displays a confirmation alert.
Form Events
Handling Form Submission with Submit and Reset Events
Forms can trigger events like submit and reset which can be handled to perform actions such as validation or data processing.
<!DOCTYPE html>
<html>
<head>
<title>Form Events</title>
</head>
<body>
<form id="userForm">
<input type="text" id="username" name="username" placeholder="Username" />
<input type="email" id="email" name="email" placeholder="Email" />
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<script>
const form = document.getElementById('userForm');
form.addEventListener('submit', (event) => {
event.preventDefault();
alert('Form submitted!');
// Perform form validation or data processing here
});
form.addEventListener('reset', () => {
alert('Form reset!');
});
</script>
</body>
</html>This example shows how to handle the submit and reset events of a form to perform actions such as preventing default behavior, validation, and data processing.
Handling Real-Time User Interactions
In addition to submit and reset, forms frequently use input, change, focus, and blur events to react to user interactions in real time. The input event fires immediately as the user types, while change fires when the element loses focus after its value has changed. For a deeper dive, see Events: change, input, cut, copy, paste.
<script>
const inputField = document.getElementById('username');
inputField.addEventListener('input', (e) => {
console.log('User is typing:', e.target.value);
});
inputField.addEventListener('change', (e) => {
console.log('Value changed:', e.target.value);
});
</script>Collecting All Form Data with FormData
Reading each field by hand is fine for two inputs, but for larger forms the FormData object lets you gather every named control at once. It is also the standard way to package data for fetch requests.
const form = document.getElementById('userForm');
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
// Read a single field
console.log(formData.get('username'));
// Iterate over every name/value pair
for (const [name, value] of formData.entries()) {
console.log(`${name}: ${value}`);
}
// Convert to a plain object (handy for JSON APIs)
const data = Object.fromEntries(formData.entries());
console.log(data); // { username: '...', email: '...' }
// Send it to a server
// fetch('/api/users', { method: 'POST', body: formData });
});Only controls that have a name attribute are included, which mirrors how a browser submits a form natively.
Validation and Preventing Default Behavior
Validating Form Data
Client-side validation can be performed to ensure data correctness before form submission.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form id="userForm">
<input type="text" id="username" name="username" placeholder="Username" required />
<input type="email" id="email" name="email" placeholder="Email" required />
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('userForm');
form.addEventListener('submit', (event) => {
event.preventDefault();
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
if (!username || !email) {
alert('Please fill in all fields.');
return;
}
// Modern approach: use checkValidity() for built-in validation
if (!form.checkValidity()) {
form.reportValidity();
return;
}
// Fallback/custom regex validation if needed
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
alert('Please enter a valid email address.');
return;
}
alert('Form submitted successfully!');
});
</script>
</body>
</html>This example demonstrates client-side form validation, including required fields and email format validation, and preventing form submission if validation fails.
Use querySelector and querySelectorAll for efficient form element selection, and always validate input values before form submission to ensure data integrity and a seamless user experience.
Client-side validation improves user experience but is not a substitute for server-side validation. Always validate and sanitize data on your backend as well.
Conclusion
Working with forms in JavaScript involves accessing form elements, getting and setting input values, collecting data with FormData, handling form events, and validating form data. By mastering these techniques, you can create dynamic and responsive web forms that enhance user interaction and data collection. To go further, explore Forms: event and method submit and Form Properties and Methods.