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;
    }
};