Wednesday, June 1, 2011

Warning if leaving a form with unsaved changes

I had a requirement to show a warning if the user was about to leave a form with unsaved changes.

One approach is to save the contents of form fields when the document is loaded and then register an "onbeforeunload" function that compares the current values with the values saved previously.

This is actually quite easy to do with jQuery. One simple approach is the following:

The serialize() function encodes form elements as a String. In this case it's all the input fields contained in a form but it could be some other HTML element.

After that it's all a matter of calling a function that will decide if the warning will be displayed or not. Returning any text from the onbeforeunload event displays a standard warning upon leaving a page.