Confirm to leave the page when editing a form with jQuery

前端 未结 5 2098
无人共我
无人共我 2020-12-05 00:50

I am coding a form and I need a function like stackoverflow have: \"You have started writing or editing a post.\".

I\'ve looked through the code of stackoverflow to

5条回答
  •  甜味超标
    2020-12-05 01:42

    small optimization of excellent Sam's answer:

    var confirm_nav_ignore = [];
    function confirm_nav() {
        var $forms = $('form'); // if you need it add .filter('#your_form_id');
    
        function save_form_state() {
            var $form = $(this),
                old_state = $form.serialize();
            $form.data('old_state', old_state);
        }
    
        $forms
            // On load, save form current state
            .each(save_form_state)
            // On submit, save form current state
            .submit(save_form_state)
        ;
    
        // strip fields that we should ignore
        function strip(form_data) {
            for (var i = 0; i < confirm_nav_ignore.length; i++) {
                var field = confirm_nav_ignore[i];
                form_data = form_data.replace(new RegExp("\\b" + field + "=[^&]*"), '');
            }
    
            return form_data;
        }
    
        // Before unload, confirm navigation if any field has been edited
        $(window).on('beforeunload', function(e) {
            var rv = undefined;
    
            $forms.each(function() {
                var $form = $(this);
                var old_state = strip($form.data('old_state'));
                var new_state = strip($form.serialize());
                if (new_state !== old_state) {
                    e.preventDefault();
                    rv = '';
                }
            });
    
            return rv;
        });
    }
    // I call it at the end of the on-load handler:
    $(confirm_nav);
    

    tested on last chrome, firefox and safari

提交回复
热议问题