Activating OnBeforeUnload ONLY when field values have changed

后端 未结 7 2070
暗喜
暗喜 2020-12-31 01:27

What I\'m trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.

I\'ve managed to g

7条回答
  •  轮回少年
    2020-12-31 02:17

    I had a similar requirement so came up with following jQuery script:

    $(document).ready(function() {
        needToConfirm = false; 
        window.onbeforeunload = askConfirm;
    });
    
    function askConfirm() {
        if (needToConfirm) {
            // Put your custom message here 
            return "Your unsaved data will be lost."; 
        }
    }
    
    $("select,input,textarea").change(function() {
        needToConfirm = true;
    });
    

    The above code checks the needToConfirm variable, if its true then it will display warning message. Whenever input, select or textarea elements value is changed, needToConfirm variable is set to true.


    PS: Firefox > 4 don't allow custom message for onbeforeunload.
    Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=588292


    UPDATE: If you are a performance freak, you will love @KyleMit's suggestion. He wrote a jQuery extension only() which will be executed only once for any element.

    $.fn.only = function (events, callback) {
        //The handler is executed at most once for all elements for all event types.
        var $this = $(this).on(events, myCallback);
        function myCallback(e) {
            $this.off(events, myCallback);
            callback.call(this, e);
        }
        return this
    };    
    
    $(":input").only('change', function() {
        needToConfirm = true;
    });
    

提交回复
热议问题