janhartmann
janhartmann

Reputation: 15003

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:

var somethingchanged = false;
$(".container-box fieldset input").change(function() {
   somethingchanged = true;
});

And a function which waits on window.onload and fires this:

window.onbeforeunload = function(e) {
    if (somethingchanged) {
        var message = "Fields have been edited without saving - continue?";
        if (typeof e == "undefined") {
            e = window.event;
        }
        if (e) { 
             e.returnValue = message;
        }
        return message;
    }
}

But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?

Thanks

Upvotes: 0

Views: 2702

Answers (2)

MunkiPhD
MunkiPhD

Reputation: 3644

Yes. Check to see that the button clicked is not the save button. So it could be something like

if ($this.id.not("savebuttonID")) {
    trigger stuff
}

Upvotes: 0

JoshBerke
JoshBerke

Reputation: 67108

When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.

The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.

<input type="button" onclick="javascript:showDirtyPrompt=false;".../>

function unloadHandler()
{
   if (showDirtyPrompt)
   { 
    //have your regular logic run here
   }
   showDirtyPrompt=true;
}

Upvotes: 1

Related Questions