JavaScript DOM Forms

Forms are an essential part of web development, allowing users to input data that can be processed and validated.

The Document Object Model (DOM) provides various methods and properties to interact with forms and their elements in JavaScript.

Let's see how to handle form using DOM in this chapter.

Accessing Form Elements

Accessing form elements is the first step in interacting with forms via the DOM.

JavaScript provides several methods to select form elements, such as getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() and querySelectorAll().

// Accessing form elements
const form = document.getElementById("myForm");
const username = document.getElementsByClassName("username")[0];
const email = document.querySelector('input[type="email"]');


console.log(form); // Logs the form element         
console.log(username); // Logs the input element with name 'username'         
console.log(email); // Logs the input element of type 'email'          

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" method="POST">
      <label for="username">Name:</label>
      <input type="text" class="username" id="username" name="username">
      <label for="email">Email:</label>
      <input type="email" id="email" name="username">
    </form>
    <script>
      const form = document.getElementById("myForm");
      const username = document.getElementsByClassName("username")[0];
      const email = document.querySelector('input[type="email"]');
      
      console.log(form); // Logs the form element         
      console.log(username); // Logs the input element with name 'username'         
      console.log(email); // Logs the input element of type 'email'          
    </script>
  </body>
</html>

Retrieving and Setting Form Values

To retrieve and set values of form elements, you can use the valueproperty.

This allows you to programmatically manipulate user inputs.

// Retrieving and setting form values
const username = document.getElementsByClassName("username")[0];
const email = document.querySelector('input[type="email"]');

// Setting values
username.value = "JohnDoe"
email.value = "john.doe@example.com"

// Retrieving values
console.log(username.value); // Logs the value of the username input        
console.log(email.value); // Logs the value of the email input          

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" method="POST">
      <label for="username">Name:</label>
      <input type="text" class="username" id="username" name="username">
      <label for="email">Email:</label>
      <input type="email" id="email" name="username">
    </form>
    <script>
      const username = document.getElementsByClassName("username")[0];
      const email = document.querySelector('input[type="email"]');
      
      // Setting values
      username.value = "JohnDoe"
      email.value = "john.doe@example.com"
      
      // Retrieving values
      console.log(username.value); // Logs the value of the username input        
      console.log(email.value); // Logs the value of the email input          
    </script>
  </body>
</html>

Form Validation

Form validation ensures that the data entered by the user meets certain criteria before it is submitted.

JavaScript can be used to validate form fields by checking their values and providing feedback to the user.

// Form validation
const form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
  const username = document.querySelector("#username");
  const email = document.querySelector('#email');
  
  if (username.value.trim() === " " || email.value.trim() === " "){ 
    alert("Please fill out all required fields.");
    event.preventDefault(); // Prevents the form from being submitted
  }else if(!validateEmail(email.value)) {
    alert("Please enter a valid email address.");
    event.preventDefault(); // Prevents the form from being submitted
  }
})


function validateEmail(email){ 
  const valid = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
  return valid.test(email.trim());
}

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" action="/javascript-tutorial/editor-198" method="POST">
      <label for="username">Name:</label>
      <input type="text" class="username" id="username" name="username">
      <label for="email">Email:</label>
      <input type="email" id="email" name="email">
      <input type="submit" value="Submit">
    </form>
    <script>
      const form = document.getElementById("myForm");

      form.addEventListener("submit", function(event) {
        const username = document.querySelector("#username");
        const email = document.querySelector('#email');
        
        if (username.value.trim() === " " || email.value.trim() === " "){ 
          alert("Please fill out all required fields.");
          event.preventDefault(); // Prevents the form from being submitted
        }else if(!validateEmail(email.value)) {
          alert("Please enter a valid email address.");
          event.preventDefault(); // Prevents the form from being submitted
        }
      })
      
      
      function validateEmail(email){ 
        const valid = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
        return valid.test(email.trim());
      }
    </script>
  </body>
</html>

Handling Form Submissions

Handling form submissions allows you to control what happens when the form is submitted.

This can include preventing the default form submission behavior, processing the form data, and sending it to a server.

// Handling form submissions
const form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
  event.preventDefault(); // Prevents the default form submission
  
  let formData = new FormData(form);
  
  fetch("submit", {
    method:"POST",
    body: formData
  })
  .then(response => response.json())
  .then(data => {
    console.log("Success:", data);        
    alert("Form submitted successfully!");
  })
  .catch(error => {
    console.log("Error:", data);        
    alert("There was an error submitting the form.");
  })
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" action="/javascript-tutorial/editor-199" method="POST">
      <label for="username">Name:</label>
      <input type="text" class="username" id="username" name="username">
      <label for="email">Email:</label>
      <input type="email" id="email" name="email">
      <input type="submit" value="Submit">
    </form>
    <script>
      const form = document.getElementById("myForm");

      form.addEventListener("submit", function(event) {
        event.preventDefault(); // Prevents the default form submission
        
        let formData = new FormData(form);
        
        fetch("submit", {
          method:"POST",
          body: formData
        })
        .then(response => response.json())
        .then(data => {
          console.log("Success:", data);        
          alert("Form submitted successfully!");
        })
        .catch(error => {
          console.log("Error:", data);        
          alert("There was an error submitting the form.");
        })
      })
    </script>
  </body>
</html>

Manipulating Form Elements

JavaScript allows you to dynamically add, remove, or modify form elements.

This can be useful for creating interactive forms that adjust based on user input or other conditions.

// Manipulating form elements
const form = document.getElementById("myForm");

// Adding a new input element
const newInput = document.createElement("input");
newInput.type = "text"
newInput.name = "newField"
newInput.placeholder = "Enter something..."
form.appendChild(newInput);

// Removing an existing input element
const username = document.getElementsByClassName("username")[0];
form.removeChild(username);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" action="#" method="POST">
      <input type="text" class="username" id="username" name="username">
      <input type="submit" value="Submit">
    </form>
    <script>
      const form = document.getElementById("myForm");

      // Adding a new input element
      const newInput = document.createElement("input");
      newInput.type = "text"
      newInput.name = "newField"
      newInput.placeholder = "Enter something..."
      form.appendChild(newInput);
      
      // Removing an existing input element
      const username = document.getElementsByClassName("username")[0];
      form.removeChild(username);
    </script>
  </body>
</html>

Accessing Form Data

Accessing form data programmatically can be achieved using the formDataobject.

This is useful for collecting all form data and processing or sending it via AJAX.

// Accessing form data
const form = document.getElementById("myForm");
let formData = new FormData(form);

for(let [name, value] of formData.entries()) { 
  console.log(`${name}: ${value}`);        
}
<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <form id="myForm" action="#" method="POST">
      <label for="username">Name:</label>
      <input type="text" class="username" value="John Doe" id="username" name="username">
      <label for="email">Email:</label>
      <input type="email" id="email" value="johndoe@email.com" name="email">
      <input type="submit" value="Submit">
    </form>
    <script>
    const form = document.getElementById("myForm");
    let formData = new FormData(form);
    
    for(let [name, value] of formData.entries()) { 
      console.log(`${name}: ${value}`);        
    }
    </script>
  </body>
</html>

DOM forms in JavaScript offer powerful capabilities for interacting with user input, validating data, handling submissions, and dynamically manipulating form elements.

Whether it's accessing and setting form values, validating inputs, handling submissions, or manipulating form elements, understanding DOM forms is essential for effective web development.

Let's learn about DOM CSS in the next chapter.