How to detect unsaved data in a form when a user leaves a page?

I need to detect unsaved data in the form when the user leaves the page without submitting the form. I would like to implement this without adding a value change listener to each input.

This is a functional requirement:

"The user opens the page than clicking on any link if the values ​​on the page have changed the warning popup to notify the user about the need to save the changed data, but if it had not changed, the system would continue without notifying the user."

I tried to compare the array method to compare both the DTO going for the database and the DTO binding, but this gives me a lot of problems in the length of the array and comparing the bytes.

+7
source share
2 answers

This is usually done on the client side using JavaScript, because it is not possible to intercept the beforeunload event on the server side when the end user leaves the page.

Here is a specific example using the jQuery JavaScript library (otherwise you will have 10 times more code to match crossbrowser compatibility and work seamlessly with ajax re-render):

 <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(function() { // Set the unload message whenever any input element get changed. $(':input').on('change', function() { setConfirmUnload(true); }); // Turn off the unload message whenever a form get submitted properly. $('form').on('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 into your <h:head> template or just put it in some script.js file that you will include <h:outputScript> .

+17
source

It worked for me.

 $(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; } 
0
source

All Articles