Friday, October 31, 2008

Leave Page Without Saving Warning

Let's say that you have a web application in which people enter a lot of information and to make sure they don't loose any information before they leave the page or close the browser by warning them that something has changed and not saved. This code uses jQuery, but is not jQuery dependent, it is just a way for me to quickly develop. for example you can use any function to set the beforeunload event with the function.

var _FormModified_ = false;
$(window).bind("beforeunload", function(e) {
    if (_FormModified_) {
        var msg = "\r\nInformation has changed.\r\nAre you sure you want to leave without saving?\r\n";
        (e || window.event).returnValue = msg;
        return msg;
    }
});

var FlagModify = function(e) {
    if (!(/^(?:9|1[6-9]|2[07]|3[3-9]|4[04-5]|9[13]|11[2-9]|12[0-3]|14[45])$/.test((e||window.event).keyCode))) 
        {_FormModified_ = true;}
};
Then on any page you want to warn on you can add this code:
$(document).ready(function(){
    $("div.inputForm input").keyup(function(e){
        FlagModify(e);
    });
    $("div.inputForm select").change(function(e){
        FlagModify(e);
    }); 
});
A bonus you get with this way of binding is that you can specify and scope which input form areas to watch. This allows you to exclude search boxes or other controls that don't need to be saved.

If AJAX or UpdatePanels are used to save the information, a client onclick event must be added which sets _FormModified_ to be false.

No comments: