JavaScript Forms
14 April 2025 | Category: JavaScript
Web forms are how users interact with websites—submitting data, signing up, logging in, searching, and more. JavaScript allows you to control, validate, and handle form data directly in the browser before sending it to the server.
đź§ What Is a Form in HTML?
A basic form contains input elements like:
<form id="myForm">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
With JavaScript, you can:
âś… Read input values
âś… Validate user input
âś… Show error messages
âś… Prevent form submission
âś… Send data using fetch()
(AJAX)
📥 Accessing Form Elements
JavaScript allows access to form elements using document.forms
.
âś… Example:
<form id="loginForm">
<input type="text" name="user" />
<input type="password" name="pass" />
</form>
<script>
const form = document.forms["loginForm"];
console.log(form.user.value); // Access the 'user' input
</script>
📌 Getting Values from Inputs
<input type="text" id="email" />
<script>
const email = document.getElementById("email").value;
</script>
Use .value
to get or set the value of an input field.
đź§Ş Form Validation (Client-side)
You can use JavaScript to validate input before the form is submitted.
âś… Example:
<form id="registerForm" onsubmit="return validateForm()">
<input type="text" id="username" placeholder="Username" />
<input type="email" id="email" placeholder="Email" />
<input type="submit" value="Register" />
</form>
<script>
function validateForm() {
const username = document.getElementById("username").value;
const email = document.getElementById("email").value;
if (username === "" || email === "") {
alert("All fields are required!");
return false; // Stops the form
}
return true; // Allows submission
}
</script>
âś‹ Preventing Default Form Submission
Sometimes, you want to handle the form with JavaScript instead of letting it reload the page.
âś… Using event.preventDefault()
<form id="customForm">
<input type="text" id="data" />
<input type="submit" value="Submit" />
</form>
<script>
document.getElementById("customForm").addEventListener("submit", function(e) {
e.preventDefault(); // Stops form from submitting normally
const val = document.getElementById("data").value;
alert("You entered: " + val);
});
</script>
📡 Submitting Form Data with JavaScript (AJAX)
<form id="myForm">
<input type="text" id="name" />
<button type="submit">Send</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault();
const name = document.getElementById("name").value;
fetch("https://example.com/api", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name }),
})
.then(res => res.json())
.then(data => console.log("Response:", data))
.catch(err => console.error("Error:", err));
});
</script>
đź§Ľ Resetting a Form
You can clear all fields like this:
document.getElementById("myForm").reset();
đź§ Summary
Task | Code Example |
---|---|
Access a form | document.forms["formName"] |
Get input value | inputElement.value |
Validate form | onsubmit="return validate()" |
Prevent form submission | e.preventDefault() |
Submit form with fetch | Use fetch() inside submit event listener |
Reset form | form.reset() |
âś… Conclusion
JavaScript makes forms powerful by allowing you to:
- Validate inputs
- Give real-time feedback
- Prevent errors
- Submit without reloading
Mastering forms is essential for building interactive websites and user-friendly interfaces.