Home >Web Front-end >JS Tutorial >JavaScript method to determine whether the user has modified the form_javascript skills

JavaScript method to determine whether the user has modified the form_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:08:471322browse

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

Copy code The code is as follows:
Click on below button. Now change some values ​​in form and click the button again.
2fda86d4b1e3d85a633406660136b8cf
f9f8cb3fc15ff683ecb7aa897331e5170c6dc11e160d3b678d68754cc175188a
b29032f60b085ba7995634e35655630f0c6dc11e160d3b678d68754cc175188a
c756ced4d8d2ce1b2bd96662c397dffc
           c6bf10f87f21e52d65963f148942bb74foo4afa15d3069109ac30911f04c56f3338
                                                                                  18bb6ffaf0152bbe49cd8a36203463410c6dc11e160d3b678d68754cc175188a
f5a47148e367a6035fd7a2faa965022e
952652e591fede9a3a3f5597cc096fc6Click to check if Form is Dirty65281c5ac262bf6d81768915a4a77ac0
0c6dc11e160d3b678d68754cc175188a
3f1c4e4b6b16bbbd69b2ee476dc4f83a
function formIsDirty(form) {
for (var i = 0; i fe97a6c0b79acd887dc26c57434eb3c2
I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
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