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.

Dom Forms in JavaScript

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 / MethodDescription
form.elementsCollection of form controls
input.valueCurrent value of an input field
form.submit()Programmatically submit the form
form.reset()Reset form to initial values
input.checkedFor 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.forms or 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?

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