I want to warn user of any unsaved data in a form before he/she clicks on a link to navigate away from the current page, without saving. What would be a better approach to achieve this in JSF, so that this check is done at one single place for all pages. Any suggestions are appreciated.
The standard JSF implementation doesn't provide facilities for this out the box. Besides, this is more a client side issue than a server side issue, so you'll really need to grab a client side language for this such as JavaScript. Since writing crossbrowser compatible JavaScript code for this particular functional requirement isn't exactly trivial, you'd like to use a JavaScript library for this which takes this into account, like jQuery.
Here's a complete kickoff example of how you could achieve this with help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(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.
$('form').submit(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;
}
</script>
Just paste this in your <head>
template (and preferably also refactor that raw <script>
code into its own .js
file as well which you include by src
attribute) and it'll work regardless of the page you have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With