Javascript – Unsaved changes warning popup

asp.netjavascriptjquery

I'm trying to implement a "Unsaved changes" warning in my web application but I'm struggling to get this working properly. I know about the existence of onbeforeunload event in javascript, but I was requested to use a custom div with some fancy formatting as a modal popup to prompt the user about those unsaved changes.

What I've got so far is this:

Basically what it does is bind a function that would check if the page is dirty and prompt the user with the popup before clicking any link or button, etc that could cause a postback. One of the problems I'm having right now is that all the cancelled events seem to be running when I press continue, instead of just the last one.

I know it is not the best solution, but it is the only thing that came to my mind. Better ideas are welcome 🙂

jQuery function to bind an event before all the others:

$.fn.bindFirst = function(name, fn) {
    this.bind(name, fn);
    var handlers = this.data('events')[name.split('.')[0]];
    if (handlers.length) {
        var handler = handlers.pop();
        handlers.splice(0, 0, handler);
    }
};

function hideSaveWarning() {
    $("#divSaveWarning").hide();
}

This will set the continue button to do the cancelled action

function showSaveWarning(e) {
    $("#divSaveWarning").show();
    $("[id$='_btnContinue']").click(function() {
        e.currentTarget.click();
    });
}

function onClickContinueWithoutSaving() {
    hideSaveWarning();
    setDirtyContent(false);
}

function SetSavePrompt() {
    setDirtyContent(false);
    $(":input, :radio, :button, a").not("[id$='_btnSave']").bindFirst('click', function(e) {
        if (isPageDirty) {
            showSaveWarning(e);
            return false;
        }
    });
}

Thanks.
Regards.

Best Answer