Create Submit and Clear Buttons for Form Submission in JavaScript



Form handling is a fundamental aspect of web development. A Submit button sends the form data for processing, while a Clear button allows users to reset or empty the form inputs. This functionality enhances user experience and ensures proper data entry.
In this tutorial, we'll learn how to create a form with a Submit button for handling submissions and a Clear button for resetting inputs using JavaScript. We'll also handle the actions triggered by these buttons effectively.

Creating a submit button for form submission

Below is an example of creating a submit button for form submission and another button to clear input ?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form with Submit and Clear Buttons</title>
</head>
<body>
    <h2>Form with Submit and Clear Buttons</h2>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" placeholder="Enter your name">
        <br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" placeholder="Enter your email">
        <br><br>
        <!-- Submit and Clear Buttons -->
        <button type="button" id="submitBtn">Submit</button>
        <button type="button" id="clearBtn">Clear</button>
    </form>

    <!-- JavaScript -->
    <script>
        // Get references to the form and buttons
        const form = document.getElementById("myForm");
        const submitButton = document.getElementById("submitBtn");
        const clearButton = document.getElementById("clearBtn");

        // Submit button functionality
        submitButton.addEventListener("click", () => {
            // Collect form data
            const formData = new FormData(form);
            const name = formData.get("name");
            const email = formData.get("email");

            // Validate inputs
            if (!name || !email) {
                alert("Please fill out all fields!");
                return;
            }

            // Display the form data (or send it to a server)
            console.log(`Name: ${name}`);
            console.log(`Email: ${email}`);
            alert("Form submitted successfully!");
        });

        // Clear button functionality
        clearButton.addEventListener("click", () => {
            form.reset(); // Reset the form fields
            alert("Form cleared!");
        });
    </script>
</body>
</html>

To run the above program, save the file name "anyName.html(index.html)" and right click on the file. Select the option "Open with Live Server" in VS Code editor.

Output

This will produce the following output ?

Now, I am going to enter some value into the text box ?


Now, I am going to click the button Delete. On clicking, you will get an alert message ?

After clicking the OK button, you will get the following output ?


Code explanation

HTML Setup:

  • The form has two input fields: name and email.
  • The Submit and Clear buttons have type="button" to prevent default form submission.
  • id attributes are added for JavaScript to target the elements.

JavaScript Functionality:

Submit Button:

  • Attach a click event listener to the button.
  • Collect the input values using FormData.
  • Validate the inputs to ensure fields are not empty.
  • Display the data in the console or send it to a server.

Clear Button:

  • Attach a click event listener to the button.
  • Use form.reset() to clear all input fields.

Alerts and Logs:

  • Alerts notify the user about successful submission or clearing.
  • Logs are used to debug and display collected data in the developer console.
Updated on: 2024-11-29T19:08:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements