Display Javascript Confirmation When User Leaves a Web Page

Update: the original code did not work in Internet Explorer 6 or 7. This is because change events for form elements do not bubble in Internet Explorer. That is lame. In any case, the included code has been tested for Firefox 3, Internet Explorer 6 and 7.

Our customer wanted to warn users that if they leave the current page with unsaved changes, those changes will be lost. The requirement is to only show an alert/confirmation when the user has changed the form but did not submit the form. However, don't forget that if the user changed the form but then clicked Submit, no confirmation or warning should be displayed (as they are saving the changes before they leave the page via the submit.)

The following Javascript is one way to do it. Note that I am using both Prototype and Ext JS in this snippet.

Ext.onReady(function() {
Ext.namespace('Dses');
Dses.formChanged = false;
$$('form.watch-for-changes').each(function(form, index) {
form.getElements().each(function(element, elIndex) {
element.observe('change', function() { Dses.formChanged = true; });
});
});
$$('form.watch-for-changes').each(function(form, index) {
form.observe('submit', function() { Dses.formChanged = false; });
});
window.onbeforeunload = function () {
if (Dses.formChanged) {
return "You have unsaved changes in your form.  You may wish to save the form before leaving this page.";
}
}
});


Note that this requires any form that you want to monitor for changes to be given the class watch-for-changes.

Read up on more details and information on Javascript, the back button, and window.onbeforeunload.
10 comments

Popular posts from this blog

Converting Array to List in Scala

I ported a JavaScript app to Dart. Here's what I learned.

Minification is not enough, you need tree shaking