A2oz

How to Get Form Data on Button Click in JavaScript?

Published in JavaScript 2 mins read

You can access form data on button click using JavaScript by targeting the form elements and their values. Here's a breakdown of how to do it:

1. Get the Form Element

First, you need to select the form element using JavaScript. You can achieve this using the getElementById() method, providing the ID of your form as an argument.

const myForm = document.getElementById("myForm"); 

2. Add an Event Listener to the Button

Next, you need to attach an event listener to the button that triggers the data retrieval process. This listener will execute a function when the button is clicked.

const submitButton = document.getElementById("submitButton"); 
submitButton.addEventListener("click", getFormData);

3. Create a Function to Retrieve Data

Define a function, like getFormData, to handle the data retrieval logic. Inside this function, you can access the form elements and their values using the elements property of the form object.

function getFormData() {
  // Accessing form data
  const name = myForm.elements["name"].value;
  const email = myForm.elements["email"].value;
  const message = myForm.elements["message"].value;

  // Do something with the data
  console.log("Name:", name);
  console.log("Email:", email);
  console.log("Message:", message); 
}

4. Handle Data

Once you have the data, you can use it in various ways:

  • Display it on the page: You can use the data to update the content on the page, for example, by displaying it in a new section.
  • Send it to a server: You can use AJAX or fetch to send the form data to a server for processing or storage.
  • Validate the data: You can implement client-side validation to ensure the data meets specific requirements.

Example:

<!DOCTYPE html>
<html>
<head>
  <title>Form Data Example</title>
</head>
<body>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <label for="message">Message:</label>
    <textarea id="message" name="message"></textarea><br><br>
    <button type="button" id="submitButton">Submit</button>
  </form>

  <script>
    const myForm = document.getElementById("myForm");
    const submitButton = document.getElementById("submitButton");

    submitButton.addEventListener("click", getFormData);

    function getFormData() {
      const name = myForm.elements["name"].value;
      const email = myForm.elements["email"].value;
      const message = myForm.elements["message"].value;

      console.log("Name:", name);
      console.log("Email:", email);
      console.log("Message:", message);
    }
  </script>
</body>
</html>

This example demonstrates how to retrieve form data on button click and display it in the console.

Related Articles