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.
9 comments:
You're not accounting for forms that are submitted by not clicking the submit button. For example, when you hit 'enter' in a text field. Might want to hook into the onsubmit event of the form instead of the submit buttons.
Ah, good point! I'll give it a shot. Mahalo!
Some controls don't fire change events until they lose focus - and I would imagine this would mean the form's change event wouldn't fire until this time as well. If that is the case you might want to switch to using Prototype's Form.Observer object which will repeatedly serialize the form on a timer and then fire a change when the serialization changes.
http://www.prototypejs.org/api/timedObserver#method-form.observer
As always, David, you're totally right. Thanks for the tip.
I've been playing with it, and the act of trying to leave the page will make the control lose focus. I've tried it on select boxes and text fields (so far) and it works as originally coded. I'll try more controls like check boxes, but so far so good.
Ah, thanks, thats good to know. After I posted I began to wonder if using the browsers "Home" or other navigation buttons would allow the losing focus event to occur first - and I hate to have that Javascript executing on a timer when not needed.
And of course this doesn't work on Internet Explorer 6 or 7. arg
[...] Display Javascript Confirmation When User Leaves a Web Page … [...]
Hi there
If anyone knows or provide..
I need UK VPN account.. (to bypass unblock etc..)
I already have USA vpn account..
I dont want to provide vpn service..
I want to buy and enjoy one..
Post a Comment