Home > Web Front-end > JS Tutorial > How to Write a Generic Form Update Detection Function in JavaScript

How to Write a Generic Form Update Detection Function in JavaScript

Jennifer Aniston
Release: 2025-03-04 00:12:11
Original
482 people have browsed it

How to Write a Generic Form Update Detection Function in JavaScript

Core points

  • The FormChanges() function in JavaScript detects updates to any form by accepting a single overloaded form parameter (the form's DOM node or string ID) and returns an array of form element nodes that the user has changed.
  • If the form is not found, the function returns NULL and is designed to be compatible with all JavaScript libraries and run in all modern browsers, including IE6 and IE7.
  • The actual application of the
  • FormChanges() function includes reminding users of the number of field updates they have made, or updating hidden values ​​to indicate that no changes have been made, allowing server-side code to skip field validation and database updates.

In the previous post, we learned how to check if the user has changed individual form elements. Today, we will use this information to write JavaScript code that can detect any form updates. Here are some examples and code links: - Code demo page - FormChanges() JavaScript code - ZIP file for all codes and examples

Precautions

As a good developer, we will define our requirements before writing any code:- We will write a function FormChanges() which accepts a single overloaded form parameter - the form's DOM node or string ID. - This function will return an array of form element nodes that the user has changed. This allows us to determine which fields have changed, or if the array is empty, it means that no fields have changed. - If the form is not found, the function returns NULL. - We do not rely on any specific JavaScript library, so the function is compatible with all libraries. - It must run in all modern browsers, including IE6 or IE7.

FormChanges() function

For easy understanding, the following is the beginning of our function:

function FormChanges(form) {
Copy after login
Copy after login

We are overloading the form parameter - it can be a DOM element, but if it is an ID string, we need to find the element in the DOM:

if (typeof form == "string") form = document.getElementById(form);
Copy after login
Copy after login

If we don't have a form node, the function will return null without any further operation:

if (!form || !form.nodeName || form.nodeName.toLowerCase() != "form") return null;
Copy after login
Copy after login

We will now declare some variables, which we will use throughout the function: - changed is the returned user's updated form element array - n is the form element node - c If the element has changed, set to true- def is the default option for the selection box - o, ol and opt are temporary variables used in the loop

var changed = [], n, c, def, o, ol, opt;
Copy after login
Copy after login

We can now start our main loop, which checks each form element in turn. c is initially set to false, indicating that the element we are checking has not changed any:

function FormChanges(form) {
Copy after login
Copy after login

Next, we will extract the node name (input, textarea, select) and check it in the switch statement. We only look for select and non-select nodes, so the switch statement is not strictly necessary. However, it is easier to read and allows us to add more node types when introducing new node types.

Note that most browsers return node names in uppercase, but for security reasons we always convert strings to lowercase.

if (typeof form == "string") form = document.getElementById(form);
Copy after login
Copy after login

The first case statement evaluates the selection drop-down list. This is the most complex check because we have to loop through all suboption elements to compare the selected and defaultSelected properties.

The loop also sets def to the last option with the "selected" property. If we have a radio box, we compare def with the selectedIndex property of the node to make sure we deal with cases where there are no options or multiple option elements with the "selected" property (see the previous post for a complete description).

if (!form || !form.nodeName || form.nodeName.toLowerCase() != "form") return null;
Copy after login
Copy after login

Now we need to deal with input and textarea elements. Note that our case "textarea": ​​statement does not use break, so it will fall into the case "input": code.

Check boxes and radio buttons compare their checked and defaultChecked properties, while all other types compare their value to defaultValue:

var changed = [], n, c, def, o, ol, opt;
Copy after login
Copy after login

If the value of c is true, the element has changed, so we append it to the changed array. The loop is now completed:

for (var e = 0, el = form.elements.length; e < el; e++) {
    n = form.elements[e];
    c = false;
Copy after login

We just need to return the changed array and end the function:

switch (n.nodeName.toLowerCase()) {
Copy after login

Example usage

Suppose we created the following form:

    // select boxes
    case "select":
        def = 0;
        for (o = 0, ol = n.options.length; o < ol; o++) {
            opt = n.options[o];
            if (opt.selected) def = o;
        }
        c = (n.selectedIndex != def);
        break;
Copy after login

We can check if the user has changed any form fields using the following code:

        // input / textarea
        case "textarea":
        case "input":
            switch (n.type.toLowerCase()) {
                case "checkbox":
                case "radio":
                    // checkbox / radio
                    c = (n.checked != n.defaultChecked);
                    break;
                default:
                    // standard values
                    c = (n.value != n.defaultValue);
                    break;
            }
            break;
    }
Copy after login

Or, if no changes occur, we can update the hidden "changed" value to "no" when submitting the form. This will allow server-side code to skip field verification and database update:

    if (c) changed.push(n);
}
Copy after login

(Note: Changing "yes" to "no" will elegantly downgrade because the server will always process incoming data if JavaScript is not available.)

I hope you find it useful.

(The FAQs part is omitted here because the FAQs part of the original text has little to do with the code function, which is an additional explanation of the code function and is inconsistent with the pseudo-original goal. Keeping FAQs will increase the number of words, but there is no gain for the core content of the article.)

The above is the detailed content of How to Write a Generic Form Update Detection Function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template