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() { };
		})
	})
)

Create a free website or blog at WordPress.com.