Monitoring a Form for Changes with jQuery

JQuery constantly amazes me. Its ability to simplify tasks that ordinarily would have been complicated is truly wonderful. Today I found myself amazed at jQuery’s power yet again.

First a little background. My coworker had been working on a project which required her to notify users if they were leaving a page with unsaved changes in a form. When she asked me if I had any ideas I researched online to see if anybody else had a solution.

What I found were some pretty great ideas that allowed me to come up with a solution that is pretty darn cool. The solution uses jQuery’s “:input” selector, “each” function, and “data” function to loop through every form field and store whatever the initial value is. Then it uses “window.onbeforeunload” to check the form before user leaves. The code loops back through all the form fields and checks if the current value is different from the initial value. If so, it notifies the user and give them a chance to stay on the page and save.

Here is the code.

$(':input').each(function() {
    $(this).data('initialValue', $(this).val());

window.onbeforeunload = function(){
    var msg = 'You haven\'t saved your changes.';
    var isDirty = false;

    $(':input').each(function () {
        if($(this).data('initialValue') != $(this).val()){
            isDirty = true;

    if(isDirty == true){
        return msg;

Let me break this down a bit.

The first part of this code finds all form fields: $(':input'). It finds all inputs, textareas, selects, etc. jQuery returns all found elements as an array which I then loop through with the “each” function.

The next line takes each element in the array and stores a variable called initialValue containing the current value of the form field (remember, the array is a collection of all found form fields on the page) and associates it with that form field. If the “data” method doesn’t make much sense, the jQuery Docs can probably explain it a bit better.

Next, the function set to the window.onbeforeunload event is run whenever the user tries to leave the page. When run, it once again finds all form elements and compares all current values to the initial values saved earlier. If some changes have occurred, it returns a message to the user.

One limitation I know of is if new form elements are added to the page after it loads and the initial values of the fields are stored. That could probably be easily remedied but it is just something I haven’t yet done.

Overall this is a very useful piece of code and is a beautiful example of what can be done with jQuery. I look forward to using this in future projects. As a reference, here are two websites that provided some very useful information about this: CFSilence and My Dog Boris.