12. Forms and Input Handling
Forms are one of the most common ways users interact with websites. You’ve seen them on login pages, contact pages, and search bars. In this lesson, you’ll learn how to handle forms in JavaScript — reading input values, validating them, and preventing page reloads.
HTML Form Structure
<form id="signupForm">
<input type="text" id="username" placeholder="Enter username" />
<button type="submit">Submit</button>
</form>Every form starts with a `<form>` tag and usually includes one or more input fields and a button. You can give each element an `id` so you can access it in JavaScript later.
Handling Form Submission
const form = document.getElementById('signupForm');
const input = document.getElementById('username');
form.addEventListener('submit', function(e) {
e.preventDefault(); // stops the page from reloading
console.log('Username:', input.value);
});The `submit` event runs when the user clicks the submit button or presses Enter. The line `e.preventDefault()` stops the browser’s default behavior (which is to reload the page).
Basic Input Validation
if (input.value.trim() === '') {
alert('Username cannot be empty!');
} else {
alert('Welcome, ' + input.value + '!');
}You can validate user input using simple conditions. Here, `trim()` removes extra spaces before checking if the field is empty.
Real-Time Feedback
input.addEventListener('input', () => {
if (input.value.length < 3) {
input.style.borderColor = 'red';
} else {
input.style.borderColor = 'limegreen';
}
});The `input` event triggers every time the user types. Here, we use it to give real-time feedback — turning the border red for short inputs and green when it looks good.
🧠Mini Challenge
Create a small login form with **email** and **password** fields. Prevent the page reload, and display a message like ‘Login successful!’ if both fields are filled.