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

前端 未结 2 1891
不思量自难忘°
不思量自难忘° 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;
            }
    

提交回复
热议问题