Unsaved changes warning popup
<p>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.</p>

<p>What I've got so far is this:</p>

<p>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.</p>

<p>I know it is not the best solution, but it is the only thing that came to my mind. Better ideas are welcome :)</p>

<p>jQuery function to bind an event before all the others:</p>

<pre><code>$.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();
}
</code></pre>

<p>This will set the continue button to do the cancelled action</p>

<pre><code>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;
        }
    });
}
</code></pre>

<p>Thanks.
Regards.</p>
