Pages

Tuesday 5 April 2011

How to warn the user that all unsaved changes will be lost when he is leaving the page

Recently I was asked to implement the following requirement in all my webforms:
"When the user is leaving a page, the application must show a confirm dialog warning the user that if he leaves the page, will lose all unsaved changes"
I decided to implement this with jQuery because I already have included the reference in all my webforms as well as some standard scripts which I use through out my applications.

What I did was add the next lines to an existing script file:


var isEditing = false;
$(document).ready(function () {
  $(":input, :text, :password, :radio, :checkbox")
    .bind("keyup change",function () {
         isEditing = true;
    });


  $("a").click(function (event) {
    if(isEditing)
       if(!confirm("Warning message"))
          event.preventDefault();
  });
});

Certainly this Code Saved the Day, but giving a closer look at this code one can note some issues to bear in mind:
-Global variables are not a good practice
-The dialog does not show up when the user close the window
-The dialog does not show up when the user clicks a button

I will fix these issues shortly, perhaps by implementing the appropriate jQuery plug-in.

No comments:

Post a Comment