Thursday, October 2, 2008

Warning Users About Unsaved Changes

I was asked to implement a popup warning to alert users they were going to lose data if they navigated away from a form without saving. It turned out to be easier than I thought by using window.onbeforeunload



<script language="javascript">
var doCheck = false;
window.onbeforeunload = checkSave;

function mustCheck() {
doCheck = true;
}

function checkSave() {
if (doCheck) {
return "You have some changes that have not been saved. If you CONTINUE, your changes WILL BE LOST.";
}
}
</script>

And then adding a startup script in the FormView PreRender

ClientScript.RegisterStartupScript(Me.GetType, "mustCheck", "mustCheck();", True)

UPDATE - You have to add the following attribute to any buttons that do not need the warning (Cancel, Save, etc.):

OnClientClick="doCheck = false;"

No comments: