Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 7 - Form Handling

7.2 Submission Handling

In the previous section, we created the HTML form and learned how to retrieve the input values.

Now, we need to implement a form submission handler. When a user clicks the submit button within the <form>, the form is automatically submitted. We want to intercept this process, prevent the default submission behavior, capture the input values, and display them somewhere.

Adding a submit Event Listener

// Access the form element
const formElement = document.getElementById('userForm');

// Add Submit Handler
formElement.addEventListener('submit', function(event) {
    event.preventDefault();
    // Callback Handler
});

The callback handler function is executed when the form is submitted.

Example:

document.getElementById('userForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    document.getElementById('responseMessage').innerText = `Submitted! Username: ${username}, Email: ${email}`;
});

This code prevents the default form submission behavior, retrieves the input values for username and email, and then displays a message with the submitted values.

Complete Example:

<!DOCTYPE html>
<html>
<head>
  <title>Form Handling</title>
</head>
<body>
  <form id="userForm">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">Submit</button>
  </form>
  <p id="responseMessage"></p>

  <script>
    document.getElementById('userForm').addEventListener('submit', function(event) {
      event.preventDefault();
      const username = document.getElementById('username').value;
      const email = document.getElementById('email').value;
      document.getElementById('responseMessage').innerText = `Submitted! Username: ${username}, Email: ${email}`;
    });
  </script>
</body>
</html>