Be so kind and warn users before navigating from an unsaved formMarch 2, 2014 coffeescript jQuery
I lost the text of the article I was just writing because I accidentally hit the Chrome shortcut for “Back” -
Cmd+[ - it’s the same key that un-indents text in Sublime Text. So now I’m writing this new article after fixing my form.
The thing is, preventing such data loss by adding a confirmation dialog on navigation is dirt simple and could even be automated (so you don’t have to separately configure it for every form).
getFormData = -> $("#someform").serialize() lastSavedData = getFormData() warnOfUnsavedChanges = (e) -> if lastSavedData != getFormData() message = 'There are unsaved changes! Close form and lose them?' e?.returnValue = message return message else return null window.onbeforeunload = warnOfUnsavedChanges $('#someform').submit = -> window.onbeforeunload = null return true
serialize() is a jQuery function that encodes a form’s contents. I actually use this snippet with realtime AJAX autosaves, and when I save the form I update
lastSavedData. I also use it with the Ace code editor, so
getFormData() contains code to store the editor’s contents into a textarea element.
Some people say that you need to unbind the handler when there are no changes and no warning, but the documentation on Window.onbeforeunload clearly says that the warning is avoided by returning
Finally, form submission is considered page navigation, too, so you have to disable the warning upon submit. If you have any kind of validation on submit, make sure this handler is bound after the validation, when the form is sure to be submitted. And if you are using AJAX to save the form, you don’t need the handler at all.