Just listen to Alex

January 16, 2010

Warning your web app users about navigating away while they have unsaved changes

Filed under: programming — Tags: , — bosmeeuw @ 12:09 pm

Have you ever spent a considerable amount of time filling in a <form> on a web page, only to accidently press “Back” or otherwise navigate away from the page, losing all the information you’ve just inputted in your form?

There’s an easy way to warn users about navigating away after they’ve inputted data on a web page. Just attach an “onchange” listener to every input element on the page, and set window.onbeforeunload() to nag the user if they try to navigate away. Clear the nagger the moment a form is submitted (and the user’s changes are sent to the server).

Here’s the code, using jQuery:

$(function() {
	$('input, select, textarea').change(function() {
		window.onbeforeunload = function() {
			return "Are you sure you want to leave this page? You have unsaved changes!";
		}
	})

	$('form').submit(function() {
		window.onbeforeunload = function() { };
	})
})

If you’re using Prototype, use this (a little more verbose):

document.observe('dom:loaded', function() {
	$$('input', 'select', 'textarea').each(function(input) {
		input.observe('change',function() {
			window.onbeforeunload = function() {
				return "Are you sure you want to leave this page? You have unsaved changes!";
			}
		})
	})

	$$('form').each(function(form) {
		form.observe('submit',function() {
			window.onbeforeunload = function() { };
		})
	})
)
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: