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

前端 未结 2 1877
不思量自难忘°
不思量自难忘° 2020-11-29 05:48

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 in

相关标签:
2条回答
  • 2020-11-29 05:59

    This 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 讨论(0)
  • 2020-11-29 06:01

    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>.

    0 讨论(0)
提交回复
热议问题