Sometimes, you need to check whether the user has modified the content of a form. You can use the following technique. If the content of a form is modified, true is returned, if the content of the form is not modified, false is returned. The Code is as follows:
Copy codeThe 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 .";
}
};