JavaScript can interact with HTML forms through the DOM to read user input, validate data, and control how the form is submitted. Using properties like document.forms, form.elements, and value, you can easily access and modify form fields without reloading the page.
document.forms gives access to all forms in the page.form.elements lets you access individual fields by their name attribute.input.value gets or sets the current value of a form control.submit event is used to handle form submission in JavaScript.event.preventDefault() stops the default page reload when a form is submitted.<input> (text, password, checkbox, radio, etc.)<textarea> for multi-line text input<select> for dropdown menus<button> or <input type="submit"> to submitAccessing a form and its elements using the DOM:
Access form by name or id (using the forms collection)
const form = document.forms["myForm"];
Access input element by its name attribute
const usernameField = form.elements["username"];
Read current value
console.log(usernameField.value);
Getting and setting values of form inputs:
Get input by id
const input = document.getElementById("email");
Get current value
console.log(input.value);
Set a new value
input.value = "newemail@example.com";
HTML structure of the form:
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
<input type="submit" value="Submit" />
</form>
JavaScript to handle the form submission:
const form = document.getElementById("myForm");
form.addEventListener("submit", function (event) {
event.preventDefault();
const username = form.elements["username"].value;
alert("Username: " + username);
});
Try typing a username in the field below and clicking Submit. JavaScript will intercept the form submission, prevent the page reload, and show the value right on the page.
Submitted username will appear here.
form.elements["fieldName"] to access form controls by their name.event.preventDefault() in your submit handler when you want to handle data with JavaScript instead of reloading the page.submit) after the DOM has loaded. You can place your script at the bottom of the HTML or use DOMContentLoaded.getElementById() or form.elements["name"] and stick to a naming convention.email, password, and a <select> for user role. Read and log their values using JavaScript.submit event with event.preventDefault() and display the submitted data inside a custom <div> instead of using alert().