Search code examples
javascriptjqueryformseventsonbeforeunload

Checking for changes in a given form before unload/leave page


I have forms with about 100 input fields each (textbox, textarea, radio, checkbox, file, etc).
When the user leaves the page I need to know if some field has been modified in order to run an autosave routine.

1.- Set form_has_been_modified when any field change:

var form_has_been_modified = 0;
$("form[id^='my_form']").each(function(){
    $(":input", this).live("change", function() {
        form_has_been_modified = 1;
    });
});

2.- Warn user if some field was changed:

window.onbeforeunload = function (e) {
    if ( ! form_has_been_modified){
        return;
    }

    var message = "This page is asking you to confirm that you want to leave - data you have entered may not be saved.";

    var e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = message;
    }

    // For Safari
    return message;
};

Questions:

a.- Could this code (part 1) make too much slow the browser's user?

b.- The previous code is working very well. But in textbox/textarea input types the change event only occur when elements loses focus. So for example this code does not protect against reload page actions. There exists another better handler instead change to solve this deficiency?


Solution

  • I would use keyup, which might be close enough, although you could get some false positives.

    Also, with .on() you can replace your .each() loop with a single call (and .live() had been deprecated in 1.7+ anyway):

    $("form[id^='my_form']").on("change keyup", ":input", function() {
         form_has_been_modified = 1;
    });