Prompt User For Unsaved Activity Using Javascript

Introduction

 
While working on a large form with many text boxes and dropdowns, I felt a need to provide a confirmation message that could prevent the loss of information due to an accidental click elsewhere. So I thought I should share the solution with you, hoping it might help someone. 
 
Say you want the user to be prompted when he/she has some unsaved activity on the page. You can use the window.onbeforeunload event for this.
 
Add this in the .aspx page head:
  1. <script type="text/javascript">  
  2. window.onbeforeunload = function(e) {  
  3. var message = \"You have not saved your changes. Do you wish to leave and abandon your changes or stay on this page so you can save?\";  
  4. e = e || window.event;  
  5. if(CheckUnSavedChanges(document.forms['Form1']))  
  6. {  
  7. if (e) {  
  8. e.returnValue = message;  
  9. }  
  10. return message;}  
  11. }  
  12. function CheckUnSavedChanges(form) {  
  13.     for (var i = 0; i < form.elements.length; i++) {  
  14.         var element = form.elements[i];  
  15.         var type = element.type;  
  16.         if (type == "checkbox" || type == "radio") {  
  17.             if (element.checked != element.defaultChecked) {  
  18.                     return true;  
  19.                 }  
  20.                     }  
  21.         else if (type == "text" || type == "textarea") {  
  22.             if (element.value != element.defaultValue) {  
  23.                 return true;  
  24.             }  
  25.         }  
  26.         else if (type == "select-one" || type == "select-multiple") {  
  27.             for (var j = 0; j < element.options.length; j++) {  
  28.                 if (element.options[j].selected != element.options[j].defaultSelected) {  
  29.                     return true;  
  30.                 }  
  31.             }  
  32.         }  
  33.     }  
  34.     return false;  
  35. }  
  36. </script> 
The function "CheckUnSavedChanges" checks every checkbox, radio button, text box, text area, and dropdown to see whether there is any change made before leaving the page and if changes have been made then it will prompt for confirmation with a confirmation box.
 
Here is how it will look:
 
ConfirmationDialogue.png
 
I hope that will help someone.
 
Thanks.