Sometimes, when you need to check whether a user has modified the contents of a form, you can use the following technique, which returns true if the contents of the form are modified, and False if the contents of the form are not modified. The code is 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")) {
- if (e) {
- E.returnvalue = "You have unsaved changes.";
- }
- Return "You have unsaved changes.";
- }
- };
JavaScript checks the form data for changes