So I'm using Errors to validate information in my Spring MVC and ran into something that I wanted feedback on how others do it, as I don't really do much web programming.
What's the best way to alert a user that if they cancel, they will lose information? What I'm looking for is a way to use a have it come back to my Model and check to see if any changes were made, and if so prompt the user 开发者_Go百科to either stay on the page or lose the changes.
Is there an easy way to do this that might be Spring MVC Friendly or is the best way using JavaScript?
You'd like to hook on the beforeunload
event. This get invoked right before the page get unloaded because the user closes the browser tab/window, or navigates away by a link/bookmark, or submits the form. Just hooking on the click
event of the cancel button doesn't cover all those cases.
Here's a kickoff example:
$(document).ready(function() {
// Set the unload message whenever any input element get changed.
$(':input').change(function() {
setConfirmUnload(true);
});
// Turn off the unload message whenever a form get submitted properly.
$('.submit').click(function() {
setConfirmUnload(false);
});
});
function setConfirmUnload(on) {
var message = "You have unsaved data. Are you sure to leave the page?";
window.onbeforeunload = (on) ? function() { return message; } : null;
}
To get it to work properly, add class="submit"
to the real submit button.
You can use the Onclick function and configure your message, alert the users as they loose the information if OnClick of cancel
精彩评论