Form handling is the process of managing and processing data submitted through a form. In JavaScript, we can use DOM (Document Object Model) events and methods to handle forms.
# Accessing Form Elements
To begin manipulating a form, we first need to access the form elements. There are a few ways to do this in JavaScript:
- By using the
document.formscollection:
// Get the form element var form = document.forms["myForm"]; // Get the input element var input = form.elements["inputName"];
- By using the
getElementByIdmethod:
// Get the form element
var form = document.getElementById("myForm");
// Get the input element
var input = document.getElementById("inputName");
- By using the
querySelectormethod:
// Get the form element
var form = document.querySelector("#myForm");
// Get the input element
var input = document.querySelector("#inputName");
# Manipulating the form elements
Changing Form Element Values
Once we have accessed a form element, we can manipulate its values using the value property. For example, to set the value of an input element:
input.value = "new value";
To get the current value of an element, we can use the same value property:
var currentValue = input.value;
Changing Form Element Properties
We can also manipulate the properties of a form element using JavaScript. For example, to disable a form element:
input.disabled = true;
To make an element read-only:
input.readOnly = true;
Changing Form Element Appearance
In addition to changing the values and properties of form elements, we can also change their appearance using JavaScript. For example, to change the style of an element:
input.style.color = "red"; input.style.backgroundColor = "yellow";
To add a class to an element:
input.classList.add("myClass");
To remove a class from an element:
input.classList.remove("myClass");
Handling form elements
In addition to the general form manipulation techniques described above, there are also specific considerations for handling different types of form elements.
1. Text Inputs
Text inputs are the most common form element and are used to collect short, alphanumeric input from the user. To get the value of a text input, we can use the value property of the HTMLInputElement object:
var value = input.value;
To set the value of a text input, we can assign a value to the value property:
input.value = "New Value";
2. Radio Buttons
Radio buttons are used to present a list of options to the user, and the user can select only one option. To get the value of the selected radio button, we can use the value property of the selected HTMLInputElement object:
var radios = form.elements["groupName"]; // Get all radio buttons in the group
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
var value = radios[i].value;
break;
}
}
To set the value of a radio button, we can use the checked property:
radios[i].checked = true;
3. Checkboxes
Checkboxes are similar to radio buttons, but they allow the user to select multiple options. To get the values of the selected checkboxes, we can use the value property of the selected HTMLInputElement objects:
var checkboxes = form.elements["groupName"]; // Get all checkboxes in the group
var values = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
values.push(checkboxes[i].value);
}
}
To set the value of a checkbox, we can use the checked property:
checkboxes[i].checked = true;
4. Select Lists
Select lists are used to present a list of options to the user, and the user can select one or more options. To get the value(s) of the selected option(s), we can use the value or selectedOptions property of the HTMLSelectElement object:
var select = form.elements["selectName"];
// Get the value of the selected option
var value = select.value;
// Get the values of the selected options (for multiple select lists)
var values = [];
for (var i = 0; i < select.selectedOptions.length; i++) {
values.push(select.selectedOptions[i].value);
}
To set the value of a select list, we can use the value property:
select.value = "optionValue";
We can also use the add and remove methods to add and remove options from the select list:
var option = document.createElement("option");
option.value = "newOption";
option.text = "New Option";
// Add the option to the select list
select.add(option, select.options[0]); // Add the option before the first option in the list
// Remove the first option from the select list
select.remove(0);
5. Textarea Elements
Textarea elements are used to collect longer, multi-line input from the user. To get the value of a textarea element, we can use the value property of the HTMLTextAreaElement object:
var value = textarea.value;
To set the value of a textarea element, we can assign a value to the value property:
textarea.value = "New Value";
6. File Inputs
File inputs are used to allow the user to select a file from their device. To get the selected file, we can use the files property of the HTMLInputElement object:
var file = input.files[0]; // Get the first file in the list
The File object contains information about the selected file, such as the file name, size, and MIME type.
# Form Validation
Form validation is the process of checking that a form has been filled out correctly before it is submitted. In JavaScript, we can use the checkValidity method of the HTMLFormElement object to check if a form is valid:
if (form.checkValidity()) {
// Form is valid, submit it
form.submit();
} else {
// Form is invalid, display an error message
alert("Please fill out the form correctly!");
}
We can also use the setCustomValidity method to set a custom error message for an individual form element:
input.setCustomValidity("Please enter a valid value!");
To ensure that a form is filled out correctly, we can use HTML5 form validation attributes, such as required, pattern, and minlength. These attributes can be added to form elements to specify validation rules. For example:
<input type="text" name="username" required minlength="6">
This input element is required and must have a minimum length of 6 characters.
We can also use JavaScript to perform more advanced validation. For example, to check that a password and password confirmation field match:
if (form.elements["password"].value !== form.elements["confirmPassword"].value) {
// Passwords do not match, display an error message
alert("Passwords do not match!");
}
Note: It is a good idea to perform both client-side and server-side validation to ensure that the data entered by the user is accurate and secure.
HTML5 Form Validation Attributes
HTML5 introduced several attributes that can be used to perform basic form validation. These attributes include:
required: specifies that an input field is requiredpattern: specifies a regular expression that the input field must matchminlength: specifies the minimum length for the input fieldmaxlength: specifies the maximum length for the input fieldmin: specifies the minimum value for the input field (for number and date input types)max: specifies the maximum value for the input field (for number and date input types)
Here is an example of a form element with some of these attributes:
<input type="text" name="username" required pattern="[a-zA-Z0-9]{6,}" minlength="6" maxlength="12">
This input element is required, must contain only letters and numbers, and must be at least 6 characters and no more than 12 characters long.
Custom Validation
In addition to using HTML5 form validation attributes, we can also use JavaScript to perform custom validation. This is useful when we need to perform more advanced validation or when we need to validate fields that do not have a corresponding HTML5 validation attribute.
To perform custom validation, we can use the setCustomValidity method of the HTMLInputElement object. This method takes a string as an argument, which is the custom error message that will be displayed if the input field is invalid.
For example:
if (input.value.length < 6) {
// Input is too short, set a custom error message
input.setCustomValidity("Please enter at least 6 characters!");
} else {
// Input is valid, reset the custom error message
input.setCustomValidity("");
}
We can also use the pattern attribute in conjunction with the setCustomValidity method to perform more advanced validation. For example:
var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!regex.test(input.value)) {
// Input does not match the pattern, set a custom error message
input.setCustomValidity("Please enter a valid email address!");
} else {
// Input is valid, reset the custom error message
input.setCustomValidity("");
}
Server-Side Validation
In addition to client-side validation, it is also important to perform server-side validation to ensure the data entered by the user is accurate and secure. Server-side validation is performed on the server, after the form has been submitted, and it is typically more reliable than client-side validation because it cannot be bypassed by the user.
To perform server-side validation, we can use a server-side language (such as PHP or Python, etc) to validate the form data before it is stored in a database or used in any other way. It is a good idea to use both client-side and server-side validation to provide the best protection against invalid or malicious data.
# FormData
The FormData object is a built-in object in JavaScript that is used to store and transmit form data. It can be used to easily send form data to the server using an HTTP request, such as an AJAX request or a fetch call.
To create a new FormData object, we can use the FormData constructor:
var data = new FormData();
We can then append data to the FormData object using the append method:
data.append("key", "value");
The key is the name of the form field, and the value is the value of the field.
For example, if we have a form with an input field named “name” and a value of “John”, we can append the form data to a FormData object like this:
data.append("name", "John");
To add a file to a FormData object, we can use the append method and specify the file input element as the value:
var fileInput = document.getElementById("fileInput");
data.append("key", fileInput.files[0]);
Here, fileInput is the file input element, and files[0] is the first file in the list of selected files.
We can also add multiple files to the FormData object by using a loop:
for (var i = 0; i < fileInput.files.length; i++) {
data.append("key", fileInput.files[i]);
}
This will append all of the selected files to the FormData object using the same key.
We can also append data from a form element directly to a FormData object using the form element as an argument for the FormData constructor:
var form = document.getElementById("formId");
var data = new FormData(form);
This will append all of the form data to the FormData object, using the name of the form field as the key and the value of the field as the value.
# Sending Form Data to the Server
Once we have validated the form data and created a FormData object and appended the data to it, we can send it to the server for further processing using an HTTP request. There are several ways to send HTTP requests in JavaScript, including the XMLHttpRequest object and the fetch function.
Here is an example of using the XMLHttpRequest object to send a POST request to a server-side script:
var request = new XMLHttpRequest();
request.open("POST", "/submit.php");
request.send(data);
And here is an example of using the fetch function to send a POST request:
fetch("/submit.php", {
method: "POST",
body: data
});
Both of these examples send a POST request to the /submit.php script with the form data as the request body.
Example:
Here is a complete real-life scenario example of form handling using JavaScript and HTML that contains all types of form input, including form validations:
HTML:
<form id="contactForm">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br>
<label for="subject">Subject:</label><br>
<input type="text" id="subject" name="subject" required><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" required></textarea><br>
<label for="attachment">Attachment:</label><br>
<input type="file" id="attachment" name="attachment"><br><br>
<input type="checkbox" id="newsletter" name="newsletter">
<label for="newsletter">Sign up for our newsletter</label><br><br>
<input type="radio" id="priorityLow" name="priority" value="low">
<label for="priorityLow">Low</label>
<input type="radio" id="priorityMedium" name="priority" value="medium" checked>
<label for="priorityMedium">Medium</label>
<input type="radio" id="priorityHigh" name="priority" value="high">
<label for="priorityHigh">High</label><br><br>
<select id="department" name="department">
<option value="">- Select -</option>
<option value="sales">Sales</option>
<option value="support">Support</option>
<option value="marketing">Marketing</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
JavaScript:
// Get the form element
var form = document.getElementById("contactForm");
// Get the input elements
var nameInput = document.getElementById("name");
var emailInput = document.getElementById("email");
var subjectInput = document.getElementById("subject");
var messageInput = document.getElementById("message");
var attachmentInput = document.getElementById("attachment");
var newsletterInput = document.getElementById("newsletter");
var priorityRadios = document.getElementsByName("priority");
var departmentSelect = document.getElementById("department");
// Check if the form is valid
function validateForm() {
if (form.checkValidity()) {
// Form is valid, process the form data
processFormData();
} else {
// Form is invalid, display an error message
alert("Please fill out the form correctly!");
}
}
// Process the form data
function processFormData() {
// Create a new FormData object
var data = new FormData();
// Append the form data
data.append("name", nameInput.value);
data.append("email", emailInput.value);
data.append("subject", subjectInput.value
data.append("message", messageInput.value);
data.append("attachment", attachmentInput.files[0]);
data.append("newsletter", newsletterInput.checked);
// Get the value of the selected radio button
for (var i = 0; i < priorityRadios.length; i++) {
if (priorityRadios[i].checked) {
data.append("priority", priorityRadios[i].value);
break;
}
}
data.append("department", departmentSelect.value);
// Send a POST request to the server
var request = new XMLHttpRequest();
request.open("POST", "/submit.php");
request.send(data);
}
// Add a submit event listener to the form
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent the form from being submitted
validateForm();
});
This code defines a form with a variety of input types: text, email, textarea, file, checkbox, radio buttons, select list. It also includes HTML5 form validation attributes (required) to ensure that the form is filled out correctly.
When the form is submitted, the validateForm function is called to check if the form is valid. If the form is valid, the processFormData function is called to create a new FormData object and append the form data to it. The form data is then sent to the server using a POST request.
Practice Exercise
- You have been asked to create a survey form for a website that collects data from users. The form should include the following fields: name, age, gender, and feedback. Use HTML to create the form and JavaScript to handle the form data.
- The form data should be validated to ensure that all fields are filled out correctly. Use HTML5 form validation attributes and JavaScript to check if the form is valid before sending the data to the server.
- When the form is submitted, create a new
FormDataobject and append the form data to it. Use afetchcall to send theFormDataobject to the server. - Add a set of radio buttons to the form that allows the user to select their level of satisfaction with the website (unsatisfied, neutral, satisfied). Append the selected value to the
FormDataobject and use it to track user satisfaction levels. - Add a file input to the form that allows the user to attach a file (e.g. a screenshot) to their feedback. Append the file to the
FormDataobject and use it to process and store the file on the server.
In this tutorial, we learned how to handle forms in JavaScript. We saw how to access form data, validate it, and send it to the server for further processing. With these techniques, you should be able to manage and process form data in your web development projects.
