Archive for the ‘ Navigation ’ Category

jQuery – Prevent a User From Leaving a Page with Unsaved Data

It’s pretty common to see the age old message ‘Are you sure you want to leave this page? Any unsaved data will be lost’ and for good reason, its useful. jQuery makes creating a message that prevents users from leaving the page pretty easy.

I recently had to implement a message just like this and to do so, I implemented the code below. The key to setting up a function like this is the onbeforeunload command

Message

First, I created my message:

 var warnMessage = 'You have unsaved changes on this page.';

Change Event

Then, I set up an event to watch controls for changes and a boolean to save the change state:

 var formModified = new Boolean();
 formModified = false;
 $('input:not(:button,:submit),textarea,select').live('change', function () {
     formModified = true;
 });

Submit Event

Now that we have something to set the formModified to true, we need a function to set it back to false once the save button has been clicked (You can modify this to use any selector you wish):

 $('input:submit').live('click', function (e) {
     formModified = false;
 });

onbeforeunload Window Event

Finally, we need to set up a function to run when onbeforeunload is fired. Our function will return our message if any fields have been changed without clicking the submit button first.

 window.onbeforeunload = function () {
     if (formModified != false) return warnMessage;
 }

Complete Code

Here’s the completed code you’ll need:

 // Capturing when the user modifies a field
 var warnMessage = 'You have unsaved changes on this page.';
 var formModified = new Boolean();
 formModified = false;
 $('input:not(:button,:submit),textarea,select').live('change', function () {
     formModified = true;
 });
 // Checking if the user has modified the form upon closing window
 $('input:submit').live('click', function (e) {
     formModified = false;
 });
 window.onbeforeunload = function () {
     if (formModified != false) return warnMessage;
 }

And that’s all you’ll need to do, pretty simple right? Oh, make sure that you’ve included a link to the jQuery library (1.4 or above) in your project as well or jQuery won’t work. It may seem obvious but you have to cover all your bases right?

As always if you find a mistake or have any suggestions for improvements let me know!