Showing posts with label check if the form is dirty. Show all posts
Showing posts with label check if the form is dirty. Show all posts

Saturday, 10 October 2015

Javascript Check if form is Dirty.


Checking if the form is dirty or not is an important scenario that comes in most web applications. Typically this implies to the fact that there is always some form in the application that will be containing atleast 20-30 fields. Here it becomes tedious to keep a track of all the values for all fields .

There are some ways to check if the form is dirty.

Approach #1

1. Serialize the form (and all its values) before showing it .
e.g
  $(document).ready(function(){   
    form_before_change = $("form").serialize();    
  });   

  
2. Serialize it again in a "onbeforeunload" event handler



 window.onbeforeunload = function (e) {   
   var form_changed = $("form").serialize();   
   if(form_before_change != form_changed) {   
    return 'There is unsaved data. on the form';   
   }   
  };