Table of Contents
Example usage
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

Mar 04, 2025 am 12:12 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1238
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles