Dom Forms in JavaScript
? DOM Forms in JavaScript
What Are DOM Forms?
A form in HTML is a container for input elements where users can enter data.
JavaScript can access and manipulate forms and their elements using the DOM.
Accessing Forms
1. By document.forms Collection
const form = document.forms[0]; // First form on the pageconst formByName = document.forms["myForm"]; // Form with name="myForm"2. By ID or Selector
const form = document.getElementById("myForm");const form = document.querySelector("#myForm");Accessing Form Elements
Form elements (inputs, selects, buttons) are accessible via the form object by name or index.
<form id="myForm"> <input type="text" name="username" /> <input type="password" name="password" /> <button type="submit">Submit</button></form><script>const form = document.getElementById("myForm");const username = form.elements["username"];console.log(username.value);</script>Listening to Form Events
Example: Handling Form Submission
form.addEventListener("submit", function(event) { event.preventDefault(); // Prevent the default form submit const username = form.elements["username"].value; alert(`Hello, ${username}!`);});Common Form Properties & Methods
| Property / Method | Description |
|---|---|
form.elements | Collection of form controls |
input.value | Current value of an input field |
form.submit() | Programmatically submit the form |
form.reset() | Reset form to initial values |
input.checked | For checkboxes/radios, whether checked |
Example: Accessing and Changing Form Input
<input type="checkbox" id="subscribe" name="subscribe"><script>const checkbox = document.getElementById("subscribe");checkbox.checked = true; // Check the boxconsole.log(checkbox.checked); // true or false</script>Validating Forms Using JavaScript
form.addEventListener("submit", function(event) { const username = form.elements["username"].value; if (username.trim() === "") { alert("Username is required!"); event.preventDefault(); }});Summary
Use
document.formsor selectors to get the form.Access inputs via
form.elements["name"].Listen for
"submit"events to handle form data.Use
.value,.checked,.reset(),.submit()to interact with inputs and forms.
Want me to show how to validate forms dynamically or how to submit forms via AJAX?