The example in this article describes how JavaScript determines whether the user has modified the form. Share it with everyone for your reference. The specific analysis is as follows:
This JS code can determine whether the user has modified the form content. If the form is modified and the browser exits, the user will be reminded whether to save the form content. It is a very useful code.
function formIsDirty(form) { for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j < element.options.length; j++) { if (element.options[j].selected != element.options[j].defaultSelected) { return true; } } } } return false; }
Usage example: When exiting the browser, if the user modifies the form, remind the user whether to save it
window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someForm"])) { // For IE and Firefox if (e) { e.returnValue = "You have unsaved changes."; } // For Safari return "You have unsaved changes."; } };
The following is a complete sample code