Leave Page Alert When Form Field Changes

This demo will show you how to monitor the form field changes, and display a message box when user try to leave the page before the submit form.

<!doctype html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="http://lereskp.github.io/jquery.formwatcher/dist/jquery.formwatcher.min.js"></script>

        <script>
            $(document).ready(function() { 
                
                $('#myForm').formwatcher().on('dirty.formwatcher', function() {
                    $("#form_changed").val('1');
                }).on('clean.formwatcher', function() {
                    $("#form_changed").val('0');
                }).on('submit', function(e) {
                    if ($(this).data('formwatcher').status !== 'dirty') {
                        // No update on the form
                        e.preventDefault();
                        alert('Don\'t submit the form, nothing has changed!');
                    } else {
                        alert('Submitting the form');
                    }
                });

                window.onbeforeunload = function confirmExit() {
                    var msg = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
                    var f_change = $("#form_changed").val();

                    if (f_change > 0) {
                        return msg;
                    }
                };

            });
        </script>
    </head>
    <body>
        <form id="myForm">
            Search: <input type="text" id="name">
            <input type="hidden" id="form_changed" value="0">
        </form>
    </body>
</html>
affiliate_link
Share this Post:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

Comments are closed.