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

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

This is the functional requirement:

"User open a page than click on any link if values in the page changed an alert message popup to notify user that he need to save changed data, but if did not change any thing system continue without notify user".

I tried to compare array method to compare both DTO coming for DB and the bind DTO, but it gives me a lot of problems in array length, and byte comparison.


Solution 1:

This is normally implemented in the client side with help of JavaScript, because it's not nicely possible to intercept on beforeunload event from the server side on when the enduser leaves the page.

Here's a concrete example with help of the JavaScript library jQuery (otherwise you would end up with 10 times as much code to make it properly crossbrowser compatible and work seamlessly together with ajax re-renders):

<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 in your <h:head> template or just put it in some script.js file which you include by <h:outputScript>.