Client/JS Framework for “Unsaved Data” Protection?

前端 未结 6 2140
一生所求
一生所求 2020-11-30 01:04

We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that st

6条回答
  •  Happy的楠姐
    2020-11-30 01:37

    I made one more slight improvement to the jQuery implementations listed on this page. My implementation will handle if you have client-side ASP.NET page validation enabled and being used on a page.

    It avoids the "error" of clearing the onBeforeLeave function when the page doesn't actually post on click due to a validation failure. Simply use the no-warn-validate class on buttons/links that cause validation. It still has the no-warn class to use on controls that have CausesValidation=false (e.g. a "Save as Draft" button). This pattern could probably be used for other validation frameworks other than ASP.NET, so I post here for reference.

     function removeCheck() { window.onbeforeunload = null; }
    
    $(document).ready(function() {
        //-----------------------------------------------------------------------------------------
        // Don't allow navigating away from page if changes to form are made. Save buttons, links,
        // etc, can be given "no-warn" or "no-warn-validate" css class to prevent warning on submit.
        // "no-warn-validate" inputs/links will only remove warning after successful validation
        //-----------------------------------------------------------------------------------------
        $(':input').one('change', function() {
            window.onbeforeunload = function() {
                return 'Leaving this page will cause edits to be lost.';
            }
        });
    
        $('.no-warn-validate').click(function() {
            if (Page_ClientValidate == null || Page_ClientValidate()) { removeCheck(); }
        });
    
        $('.no-warn').click(function() { removeCheck() });
    });
    

提交回复
热议问题