In web apps it’s helpful to warn the user if they attempt to navigate away after making changes without hitting save. But the tricky part is, how do you track when they’ve made changes? This is actually pretty trivial to pull off with a little bit of jQuery.
- Leverage the “on” function to attach an event handler to any change, keyup, or keydown events for any inputs, textareas, or selects:
Notice that whenever one of these events occurs, the class “changed-input” is assigned to the input. This comes in handy for checking if the form is “dirty” below. Also, keep in mind that the example attaches to an element with an id of body-content, but as usual with jQuery’s “on” function, for optimal performance you should choose the most specific selector possible.
- Attach to the “beforeunload” event and check if the form is dirty by seeing if any elements with a class of “changed-input” exist.
When the user tries to navigate away or hit refresh, they’ll be greeted with a friendly reminder that they haven’t saved changes. The exact look and wording differs based on browser, but the string returned is displayed as part of the message. Here’s an example using the above message with Chrome.
Sure beats the angry phone call and superfluous tickets claiming the application didn’t save!