Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Web Forms Api in JavaScript

Web Forms Api in JavaScript

Web Forms API in JavaScript


The Web Forms API in JavaScript allows developers to interact with and control HTML forms and their elements (like <input>, <select>, <textarea>, etc.) directly from JavaScript.

It provides a powerful way to validate, access, modify, and submit forms dynamically.


Basic Access to Form Elements

You can access forms using the document.forms collection:

const myForm = document.forms['myForm']; // by name attribute

Or using:

const myForm = document.getElementById('myForm'); // by id

Accessing Form Elements

<form id="loginForm">  <input type="text" name="username" />  <input type="password" name="password" /></form>
const form = document.getElementById('loginForm');const username = form.elements['username'].value;const password = form.elements['password'].value;

Form Validation

HTML5 forms support built-in validation (e.g., required, type="email"). You can access it with JavaScript:

if (form.checkValidity()) {  alert('Form is valid!');} else {  alert('Form is invalid!');}

Prevent Default Form Submission

To handle form submissions with JavaScript:

form.addEventListener('submit', function(e) {  e.preventDefault(); // Prevent page reload  console.log('Username:', form.username.value);});

Reset and Submit Methods

form.reset();   // Clears all fields to default valuesform.submit();  // Submits the form programmatically

Custom Validation Example

const email = form.elements['email'];if (!email.value.includes('@')) {  email.setCustomValidity('Email must contain @');} else {  email.setCustomValidity('');}

Summary

FeatureDescription
document.formsAccess forms in the page
form.elementsAccess individual form controls
.checkValidity()Check form validity
.reset() / .submit()Reset or submit form programmatically
e.preventDefault()Prevent default submission behavior

Would you like an example of form validation or AJAX form submission next?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql