Accessing Elements:
document.forms[0][name]; // returns a HTMLCollection, access forms using index or name attribute, and then access its inputs
form.elements.name; // any element used in forms is available inside form.elements, can use name, id, or index
document.getElementById('inputId'); // access a form input by id
document.getElementByName('name'); // access multiple inputs using the same name attribute
Accessing Data:
input.value; // returns a string, representing selected value or user input
input.checked; // returns a boolean, if checked or not
Some ways to access forms using JavaScript.
checkValidity(); // returns true if an input contains valid data.
setCustomValidity(); // sets the validationMessage property of an input element
Helps make validating forms easier.
focus // to "focus" on an element
input.onfocus = function(){ // remove error message if user wants to input something }
blur // when an element loses focus
input.onblur = function(){ // validate, show error message if failed }
elem.focus() // method used to set focus
elem.blur() // method used to unset focus
Use focus and blur events with javascript forms to add validation and other functionality.
const formElement = document.getElementById('formId');
formElement.addEventListener('submit', (event) => {
event.preventDefault(); // Prevents the default form submission
// Perform form validation or processing
// Access form input values
const inputValue = inputElement.value;
// ...
// Reset form
formElement.reset();
});
A way to handle forms, using submit event as a way to validate before sending it to a server.