Saturday, April 19, 2014

Dirty checking to warn for unsaved changes using jQuery

Copy following code snippet into the application. dirtyCount() method return the number of fields have unsaved changes.
var dirtyChecking = function () {
    $('input, select, textarea').each(function () {
        var ele = $(this);
 
        ele.attr('data-old', ele.val());
 
        // Look for changes in the value
        ele.on("change keyup paste click", function (event) {
            if (ele.attr('data-old') != ele.val()) {
                ele.addClass('unsaved');
            } else {
                ele.removeClass('unsaved');
            }
        });
    });
};
 
var dirtyCount = function () {
    return $('.unsaved').length;
};

//Call dirty checking
dirtyChecking();
Copy following code to show unsaved changes warning on form unload or can define of your own
//Bind warning message showing on form unload 
window.onbeforeunload = function (e) {
    if (dirtyCount()) {
        var message = 'Any unsaved changes will be lost.';
        e = e || window.event;

        if (e) {
            e.returnValue = message;
        }

        // For Safari
            return message;
    }
};

2 comments:

  1. Thanks for posting! The warning only fired when reloading the page, not navigating to a new page. Any ideas on how I can fix?

    ReplyDelete
    Replies
    1. Thank you your comment and using the code snippet. You can call dirty checking on window focus out.

      Move the dirty checking code into a function and call that on window unload and focus out. Follow the link to see how you can track the window losing focus - https://gist.github.com/morshedalam/84c1cda0d20b8988273b

      Delete