Friday, January 2, 2009

Prompt User About Unsaved Changes Using Mootools

Mootools has a very useful method toQueryString on the Form element class.  In short, this method takes all the form fields and builds a query string generally used when sending form data to the server.  However, I found another use for this method that I thought I would share.

For our Episodic Video Publishing Web Application we have a number of pages that include a form.  If the user tries to navigate from a form that has unsaved changes then we want to prompt the user that they have unsaved changes and that these changes will be lost if they navigate away.  There are various ways that you can detect if the user has modified the page's form but the easiest I've found is to make use of Form.toQueryString.

First, create a function that stores the form state in a hidden input.

getOrCreateInitialFormState: function(form) {
var formInitialState = null;,
var formInitialState = $('form_initial_state');
if (!formInitialState)
formInitialState = new Element('input', {
id: 'form_initial_state',
type: 'hidden',
value: form.toQueryString()
}).inject(form, 'before');
return formInitialState;

So when the page loads record the current form state and hook into the click event for any links on your page and check if the form state has changed.

window.addEvent('domready', function()
// Grab the form
var form = $('my_form');

// Store the form state in a hidden input

// Capture any clicks that would cause the user to navigate away
$$('a').addEvent('click', function(e) {
if (form.toQueryString() != getOrCreateInitialFormState(form) {
var result = confirm('You have unsaved changes.' +
' Are you sure you want to navigate away from this page?');
if (result == true) {
// The user wants to navigate
window.location.href = a.get('href');

That's it!