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.

1 comment:

  1. Manuel-- I just wanted to leave you a quick note that this code came in handy for me. I did make a small change to add some dropdowns into the mix-- but it was super easy thanks to the code you pasted here. You are right-- it is quite easy with JQuery.

    Thank you for taking the time to post this.