JavaScript's way of determining whether a user has modified a form

  • 2020-05-17 04:47:51
  • OfStack

This example shows how JavaScript can determine if a user has made a change to a form. Share with you for your reference. The specific analysis is as follows:

This JS code can tell if the user has made any changes to the form content, and if the user has made any changes to the form and exits the browser, it will remind the user whether to save the form content. This is 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;
}

Use example: when exiting the browser, remind the user whether to save the form if the user has modified 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.";
 }
};

Here is a complete example of the code

Click on below button. Now change some values in form and click the button again.
<form name="fooForm">
    <input type="text" name="t"><br>
    <input type="text" name="2" value="default"><br>
    <select name="some">
        <option value="fooo" selected="">foo</option>
        <option value="bar">bar</option>
    </select><br>
</form>
    <button onclick="alert(formIsDirty(document.fooForm))">Click to check if Form is Dirty</button>
<br>
<script>
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;
}
</script>

I hope this article is helpful for you to design javascript program.


Related articles: