I’ve got a page that should warn if the user tries to leave the page having unsaved data. This dialog means “You have unsaved data. Do you want to conitnue?”

The problem is that the form values go blank when the user clicks a link to move on and is presented with the dialog. I want to form values to stay in place so that the user actually can choose not to continue and then still have left what was entered to the form.
The way the code is now is that it keeps a flag for whether the form has dirty data and that is a hidden variable:
<input type="hidden" name="saveStatus" value="<%=saveStatus%>" />
Touching the form sets this hidden variables with onclickand onkeypressed.
On the server I’ve got some logic that checks whether data is dirty:
public boolean returnToUnsavedData(ISessionHandler sessionHandler,
Action action) {
String saveStatus = sessionHandler.getRequestParameter("saveStatus");
if (saveStatus != null && !saveStatus.trim().equals("")) {
setHasUnsavedData(true);
} else {
setHasUnsavedData(false);
}
if (hasUnsavedData()) {
if (!"menuHasUnsavedDataOk".equalsIgnoreCase(action
.getActionCommand())
&& !action.getActionName().equals("Administrera")) {
ResourceBundle messages = ResourceBundle.getBundle("messages");
UserMessage um;
if (action.getActionCommand().equals("fastsearch")) {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand(), sessionHandler.getRequest().getParameter("fastsearch"));
} else {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand());
}
action.addUserMessage(um);
action.setReturnPage(action.getCurrPage());
setLatestActionTarget(action.getActionTarget());
return true;
} else {
setHasUnsavedData(false);
}
}
return false;
}
I suppose this is where I could check serverside for the variables and repopulate everything and then use a technique like above with the hidden variable to keep form values.
Do you think that this idea will work or can you present alternative solutions?
I don’t think you need server-side involvement here, you can achieve this by using just
javascript:Register an observer before the page gets unloaded and check your
saveStatusvariable in there:However, by using this you will not have your own ‘custom’ confirmation screen, the browser’s built in confirmation will be used (similar to stack-overflow’s).