This article example describes how JS detects whether form data changes when leaving or refreshing a page. Share it for your reference, as follows:
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;}window.onbeforeunload = function (e) { e = e || window.event; if (formIsDirty(document.forms["someForm"])) { // IE and Firefox if (e) { e.returnValue = "Sorry, the page data has been modified, not saved yet, I'm sure you want to refresh or leave this page?"; } // Safari browser returns "Sorry, the page data has been modified, not saved yet, I'm sure you want to refresh or leave this page?"; }};For more information about JavaScript related content, please check out the topics of this site: "Summary of JSON operation techniques in JavaScript", "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.