Prevent a User Navigating Away from a Page with Unsaved Changes
On my current project we have the problem where users will often navigate away from a page without saving their changes. The users of our application are often unfamiliar with websites and therefore simply navigate away without hitting update (as you would if you’re only familiar with desktop applications).
To help avoid this problem we wanted to alert the user to unsaved changes, similar to what Gmail does when you navigate away with an unsaved message.
Most of what you’re after here is done through the beforeunload event. Binding to this event allows you to return a string which will be displayed to the user and prompt them to stay on the page or continue navigating away.
I implemented this with a very simple jQuery extension.
The only problem I ran into was that actually submitting the form would still prompt the user – this is why I needed to check the submit event and not prompt the user in that case.
Now I simply need to add the detect_changes class to any form and it will automatically prompt the user if they navigate away without saving. Happy coding.