Learn and share. The simplest harmony.

 

[Code Snippet] jQuery : Confirm Before Exit

Posted on March 1, 2010 and got 3 shouts so far

Gmail compose has functionality to detect any content modification and confirm us before closing browser’s window because of unsaved content that we’ve modify, yes in this post i will try to explain how to make these function work on our webapps.

 

Firstly, we create a boolean variable with default value false then we check is there any content in our input that have been modified by the user. If the user has been modified then we change the boolean variable value to true.

Now, we create a function (named checkIsEdit) to check the value of the boolean variable, if the value is true then alert the user that the’ve modify some content. And the last step, we attach checkIsEdit function to the window event (onbeforeunload) to check whether the window is being refreshed or closed and fire up the function. That’s it, check out this following code :

$(document).ready(function() {

	var isEdit	= false;

	$('input').change(function() {
		isEdit = true;
	});

	function checkIsEdit() {
		if(isEdit)
			return "You have modify some content";
	}

	window.onbeforeunload = checkIsEdit;
});

 

This Post Tags :

Bookmark Post :

  • Nice work on this one, useful in an admin application or in cooperation with an auto save script.

  • o0ooohh gtu yah…yang di pake webmessenger.yahoo.com :p

  • Great stuff! It works with the latest versions of Firefox, IE, Safari and Chrome. However, it does not seem to work with Opera 11.50.