In this new cyberworld saturated with abundant mouse clicks, it has become more necessary to try to get your user’s attention before allowing them to perform an action that may result in a critical error. One of these actions is leaving the application without first saving changes. In some cases, a request to leave a page without first saving changes may be on purpose, but in many cases it may have been the result of an accidental mouse click.
Browsers have provided a built-in prompt that warns users before leaving certain pages. The user then has the option of leaving the page or staying on the page. This built-in prompt is not at all flexible, by design, to prevent rogue sites from actually preventing users from leaving their web sites.
The following is an example of how you might implement this prompt using the window.onbeforeunload event.
STEP 1: Mechanism to determine if there are unsaved changes
Because there is no reason to warn your users from leaving if they have not made any changes, the first thing you want to do is create a hidden field or client-side variable that specifies whether your page contains unsaved changes.
In this example, I have created a hidden input to store my change status:
@Html.Hidden("UnsavedChanges", "0")
I then created a function to update the change status:
function HandleFieldChange()
{
$("#UnsavedChanges").val("1");
}
Finally, I used a little jQuery to easily add the field change event:
$("input").change(function(){
HandleFieldChange();
});
$("select").change(function(){
HandleFieldChange();
});
$("textarea").change(function(){
HandleFieldChange();
});
$("input:checkbox").click(function(){
HandleFieldChange();
});
$("input:radio").click(function(){
HandleFieldChange();
});
STEP 2: Use the browser’s built-in warning prompt before leaving a page.
Again, this cannot be customized. If it could, that would open the door for this functionality to be used maliciously. You don’t have any control over how the warning looks, but you can insert a custom message into the prompt.
This function checks to see if there are unsaved changes. If there are, it calls the browser’s built-in warning and inserts a custom message.
window.onbeforeunload = function() {
if ($("#UnsavedChanges").val() == "1")
{
var _message = "You currently have unsaved changes!!!nnAre you sure you want to exit without saving.nnChoose 'Leave this page' to exit without saving changes.nChoose 'Stay on this page' to return to the billing profile.";
return _message;
}
}
RESULT
It’s not as pretty as I would like, but it works!