When creating data entry forms in ASP .NET, the JavaScript onbeforeonload event can add a huge improvement to the end user experience. This nifty little event is fired before a page is unloaded (duh) and will keep users from navigating off of a page (and even from closing their browser) when they have unsaved changes on a data entry form.
The onbeforeunload event behaves a bit oddly for an event. Basically in your event handler function, if you return anything, the event will pop up a message box with whatever you returned sandwiched between “Are you sure you want to navigate away from this page?” and “Press OK to continue, or Cancel to stay on the current page.” Here is an example:
If, however, your function doesn’t return anything, no warning will show up (but the page is removed from cached memory so you can’t navigate back to it.) This provides a very nice tool for alerting users. All your function needs to do is to check if data has been edited and if so, return an appropriate string. The window prompt and warning will then be handled for you by the onbeforeunload event.
The function is extremely easy to use. In the “<script type="text/javascript">“ section at the end of an ASPX page you just need to assign a function to the “window.onbeforeunload” event. Below is a complete snippet (the JavaScript variable bEdited is set outside of this snippet to true if data on the form has been edited.)
var bEdited = new Boolean();
function UnLoadWindow() {
if (!(bEdited)) {
return;
}
return 'DMC strongly recommends NOT closing this window yet.';
}
window.onbeforeunload = UnLoadWindow;
Learn more about DMC's software and web development services.