js Method for detecting whether form data changes when leaving or refreshing a page

  • 2021-07-07 06:11:16
  • OfStack

This article example shows how js detects whether the form data changes when leaving or refreshing the 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 and has not been saved. Are you sure you want to refresh or leave this page? ";
    }
    // Safari Browser 
    return " Sorry, the page data has been modified and has not been saved. Are you sure you want to refresh or leave this page? ";
  }
};

More readers interested in JavaScript can check the topics of this site: "Summary of json Operation Skills in JavaScript", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Error and Debugging Skills", "Summary of JavaScript Data Structure and Algorithm Skills", "Summary of JavaScript Traversal Algorithm and Skills" and "Summary of JavaScript Mathematical Operation Usage"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: