Form Handling in JavaScript
This article is a complementary resource to the JavaScript in Browser course.
This article is a complementary resource to the JavaScript in Browser course.
Form Handling in JavaScript
Forms are a crucial component of web applications, enabling users to interact with websites by entering and submitting data.
JavaScript provides powerful tools for handling form data, validating user inputs, and creating dynamic, interactive forms.
In this article, you'll learn the fundamentals of JavaScript form handling with the help of practical examples.
JavaScript allows you to easily access the values entered by users in form elements. These include:
value property)checked property)checked and value properties)value property)Let's go through them one by one.
We use the value property to get or set the text entered in text input fields. For example, consider the following HTML code:
HTML Code
<input type="text" id="username" name="username" value="Initial Value">
Here's how you can use JavaScript to get and set the text value:
JavaScript Code
let username = document.querySelector("#username").value;
console.log(username); // Prints initial value of the text
// Setting a new value
document.querySelector("#username").value = "New User";
For checkboxes, the checked property indicates whether the checkbox is selected.
HTML Code
<input type="checkbox" id="agree" name="agree">
<label for="agree">I agree to the terms</label>
JavaScript Code
let isAgreed = document.querySelector("#agree").checked;
console.log(isAgreed); // Outputs: true if checked, false otherwise
Radio buttons require checking the checked property to determine which button is selected and accessing its value.
HTML Code
<input type="radio" id="option1" name="options" value="1">
<label for="option1">Option 1</label>
<input type="radio" id="option2" name="options" value="2">
<label for="option2">Option 2</label>
JavaScript Code
let selectedOption = document.querySelector('input[name="options"]:checked').value;
console.log(selectedOption); // Outputs: 1 or 2 depending on selection
The value property of a select element provides the value of the selected option.
HTML Code
<select id="city" name="city">
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="paris">Paris</option>
</select>
JavaScript Code
let selectedCity = document.querySelector("#city").value;
console.log(selectedCity); // Outputs: newyork, london, or paris
The submit event is triggered when a form is submitted. You can use JavaScript to handle this event and perform actions such as preventing the default submission behavior and accessing form data.
The default behavior of a form submission is to navigate to the URL specified in the action attribute or reload the page if no action is specified. To prevent this, use event.preventDefault().
HTML Code
<form id="myForm">
<input type="text" id="name" name="name"><br><br>
<button type="submit">Submit</button>
</form>
JavaScript Code
document.querySelector("#myForm").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented!");
});
You can access form data within the submit event handler using the value property of the form elements.
HTML Code
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<button type="submit">Submit</button>
</form>
JavaScript Code
document.querySelector("#myForm").addEventListener("submit", function(event) {
event.preventDefault();
let email = document.querySelector("#email").value;
console.log("Email submitted:", email);
});
This example demonstrates how to prevent the default form submission and log the form data to the console.
<!DOCTYPE html>
<html>
<head>
<title>Form Submission Example</title>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector("#myForm").addEventListener("submit", function(event) {
event.preventDefault();
let name = document.querySelector("#name").value;
let email = document.querySelector("#email").value;
console.log("Name:", name, "Email:", email);
});
</script>
</body>
</html>
Form validation is essential for ensuring that user-provided data meets the required criteria.
JavaScript allows you to perform various types of validation on the client side before submitting the form.
You can implement custom validation logic using JavaScript to check for specific conditions.
setCustomValidity() - Sets a custom error message for an input element.checkValidity() - Checks if the input element has any validity constraints and returns a Boolean value.HTML Code
<input type="email" id="email" name="email" required>
JavaScript Code
let email = document.querySelector("#email");
email.addEventListener("input", function() {
if (email.validity.typeMismatch) {
email.setCustomValidity("Please enter a valid email address.");
}
else {
email.setCustomValidity(""); // Clear the error message
}
});
Display error messages dynamically to provide real-time feedback to users.
HTML Code
<form id="myForm">
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="99"><br>
<span id="ageError" style="color: red;"></span><br>
<button type="submit">Submit</button>
</form>
JavaScript Code
document.querySelector("#myForm").addEventListener("submit", function(event) {
let age = document.querySelector("#age");
let ageError = document.querySelector("#ageError");
if (age.value < 18 || age.value > 99) {
event.preventDefault();
ageError.innerText = "Age must be between 18 and 99.";
} else {
ageError.innerText = ""; // Clear the error message
}
});
This example demonstrates how to validate an email field to ensure it contains the @ symbol.
<!DOCTYPE html>
<html>
<head>
<title>Email Validation Example</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<span id="emailError" style="color: red;"></span><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector("#myForm").addEventListener("submit", function(event) {
let email = document.querySelector("#email");
let emailError = document.querySelector("#emailError");
if (!email.value.includes("@")) {
event.preventDefault();
emailError.innerText = "Please enter a valid email!";
}
else {
emailError.innerText = "";
}
});
</script>
</body>
</html>
JavaScript allows you to create dynamic and interactive forms by listening to various events such as input, change, and keyup.
input - Triggered when the value of an element is changed.change - Triggered when the value of an element has been committed.keyup - Triggered when a key is released.HTML Code
<input type="text" id="myInput" name="myInput">
JavaScript Code
let inputField = document.querySelector("#myInput");
inputField.addEventListener("input", function() {
console.log("Input event:", this.value);
});
inputField.addEventListener("change", function() {
console.log("Change event:", this.value);
});
inputField.addEventListener("keyup", function() {
console.log("Keyup event:", this.value);
});
You can use these events to update content in real-time as users type in the form.
HTML Code
<textarea id="message" name="message" rows="4" cols="50"></textarea><br>
Character Count: <span id="charCount">0</span>
JavaScript Code
document.querySelector("#message").addEventListener("input", function() {
document.querySelector("#charCount").innerText = this.value.length;
});
This example demonstrates how to display a live character count for a textarea.
<!DOCTYPE html>
<html>
<head>
<title>Live Character Count</title>
</head>
<body>
<label for="message">Enter your message:</label><br>
<textarea id="message" name="message" rows="4" cols="50"></textarea><br>
Character Count: <span id="charCount">0</span>
<script>
document.querySelector("#message").addEventListener("input", function() {
document.querySelector("#charCount").innerText = this.value.length;
});
</script>
</body>
</html>