Javascript method for checking whether the form data is changed

Source: Internet
Author: User

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 .";
}
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.