Categories
JavaScript Answers

How to detect if HTML form is edited with JavaScript?

Spread the love

Detecting changes in an HTML form with JavaScript involves tracking the initial state of the form and comparing it to its current state.

We can achieve this by:

  1. Storing the initial state of the form when it is loaded.
  2. Setting up event listeners to detect changes to form elements.
  3. Comparing the current state of the form with the initial state to determine if it has been edited.

Here’s a basic example of how you can do this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detect Form Changes</title>
</head>
<body>
    <form id="myForm">
        <input type="text" name="firstName" placeholder="First Name">
        <input type="text" name="lastName" placeholder="Last Name">
        <button type="submit">Submit</button>
    </form>

    <script>
        // Store the initial state of the form
        var initialFormData = new FormData(document.getElementById('myForm'));

        // Add event listeners to form elements to detect changes
        var formElements = document.querySelectorAll('#myForm input');
        formElements.forEach(function(element) {
            element.addEventListener('input', handleInputChange);
        });

        // Function to handle form input changes
        function handleInputChange() {
            var currentFormData = new FormData(document.getElementById('myForm'));
            var isFormEdited = !isEqual(initialFormData, currentFormData);

            if (isFormEdited) {
                console.log('Form has been edited.');
            } else {
                console.log('Form has not been edited.');
            }
        }

        // Function to compare two FormData objects
        function isEqual(form1, form2) {
            if (form1 === form2) return true;
            if (form1 === null || form2 === null) return false;
            if (form1.size !== form2.size) return false;

            for (var pair of form1.entries()) {
                if (!form2.has(pair[0]) || form2.get(pair[0]) !== pair[1]) {
                    return false;
                }
            }

            return true;
        }
    </script>
</body>
</html>

In this example, we store the initial state of the form using FormData when the page loads.

Then we add event listeners to form input elements to detect changes. When an input element’s value changes, the handleInputChange function is called.

Inside handleInputChange, we create a new FormData object representing the current state of the form and compare it to the initial state using the isEqual function.

If the two states are different, we log a message indicating that the form has been edited.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *