How to prevent a user leaving a page with unsaved data

A lot of good websites provide a failsafe check that a user might accidentally leave a page with unsaved data. This is a good thing to have, specially in forms which are long or important. It can be done easily using jQuery and javascript.

It consists of hooking the window.onbeforeunload() event and putting a check that only if the user has not pressed a submit button that it should show a prompt.

The sample html is given below:

	<form >
		Name <input name="n"><br>
		Age <select name=cboAge>
			<option value="0">Select</option>
			<option value="10">10</option>
			<option value="20">20</option>
			</select>
			<br>
		Details <textarea name=det rows=5 cols=60></textarea><br>
		<input type=submit value="Save"><br>
		<br>
		<a href="http://www.google.com">Go away from this page</a>
		 	
	</form>

The sample javascript is given below:

var prompt=true;

		$(document).ready(function() {

				$('input:not(:button,:submit),textarea,select').change(function () {
					window.onbeforeunload = function () {
						if (prompt == true) 
							return "You have made changes to the page";
						}
					});


				$('input:submit').click(function(e) {
					prompt = false;
					});
	    });

		

Note than Firefox will not show your message but it will show its own prompt message. Other browsers will show your message. This approach also works if a person tries to close the browser window or tab or types in a new URL in the same window.

6 Comments

Leave a Reply

Your email address will not be published.


*