Prompting a User to Save Changes Before Leaving a Page Using jQuery
The first step is to know when the form is ‘dirty’ i.e. when a user has made any change to the form that has not been saved. There are a various ways to know that a form is dirty, but I chose to declare a global variable called ‘isDirty’.
There are many other ways to achieve this. If you know any other way to achieve this, do share here.
Ref: http://www.prosoxi.com/2012/06/21/jquery-method-to-prompt-a-user-to-save-changes-before-leaving-page/
var isDirty = false; $(document).ready(function() { //save all the input values to check later $('#myform input').each(function() { $(this).data('original', $(this).val()); }); $(window).bind('beforeunload', function(){ //to update the dirty flag when there is a different form values $('#myform input').each(function() { if ($(this).data('original') != $(this).val()) { isDirty = true; } }); if (isDirty) { return 'You haven\'t saved your changes.'; } }); });This method will detect if the user has made any changes in the form and alert the confirmation dialog. In this way, you can protect a user from leaving the page if there is change in the form.
There are many other ways to achieve this. If you know any other way to achieve this, do share here.
Ref: http://www.prosoxi.com/2012/06/21/jquery-method-to-prompt-a-user-to-save-changes-before-leaving-page/
Comments
Post a Comment