Wanted to expand slightly on Volomike excellent jQuery code.
So with this, we have a very very cool and elegant mechanism to accomplish the objective of preventing inadvertent data loss through navigating away from updated data prior to saving – ie. updated field on a page, then click on a button, link or even the back button in the browser before clicking the Save button.
The only thing you need to do is add a “noWarn” class tag to all controls ( especially Save buttons ) that do a post back to the website, that either save or do not remove any updated data.
If the control causes the page to lose data, ie. navigates to the next page or clears the data – you do not need to do anything, as the scripts will automatically show the warning message.
Awesome! Well done Volomike!
Simply have the jQuery code as follows:
$(document).ready(function() {
//----------------------------------------------------------------------
// Don't allow us to navigate away from a page on which we're changed
// values on any control without a warning message. Need to class our
// save buttons, links, etc so they can do a save without the message -
// ie. CssClass="noWarn"
//----------------------------------------------------------------------
$('input:text,input:checkbox,input:radio,textarea,select').one('change', function() {
$('BODY').attr('onbeforeunload',
"return 'Leaving this page will cause any unsaved data to be lost.';");
});
$('.noWarn').click(function() { $('BODY').removeAttr('onbeforeunload'); });
});