views:

48

answers:

1

I'd like to create an onbeforeunload "You have made edits to the page. Stay On This Page, Leave This Page" jQuery plugin.

The plugin will need to:

  1. Accept a containing element. $(".editableFieldContainer").beforeUnload()
  2. Autodetect changes to not(:hidden) input/textarea/selects.
  3. Prompt user to stay on the page if elements within the containing element have changed.
    • except if the page was submitted via form.
    • except if the page/user wants to cancel the changes, e.g., a "Cancel" link/button was pressed.

Something like this (but not quite, it is missing some features):

(function(){
    var changed = false;
    $.beforeUnloadCanceled = false;
    $.fn.beforeUnload = function(){
        $.beforeUnloadCanceled = true;
        return $(this).delegate("input,select,textarea", "change", function(){
            changed = true;
        });
    });
    window.onbeforeunload = function(){
        if(changed && !beforeUnloadCanceled){return "You have made edits to the page.";} 
    };
}());

Is there already a decent plugin that does this?

+1  A: 

This could be what your looking for.

jquery.wtFormDirty-2.0.2.js

code90
looks like that could do it with a little work...and the code smells like rotten eggs. But its a start. Thanks!
David Murdoch
I just made a newer version. This looks better than the old one..http://wt-plugins.googlecode.com/files/jquery.wtFormDirty-2.js
code90
check your select-list code path. it is a bit broken.
David Murdoch
thanks for pointing it out.. fixed now! http://wt-plugins.googlecode.com/files/jquery.wtFormDirty-2.0.2.js
code90
I'll mark this as the accepted answer...but first you gotta fix the select code. I don't want anyone in the future seeing this as the Accepted answer when the code doesn't work. :-)
David Murdoch
it is still not quite right. I'm putting together a fix now. i'll post it when i'm done.
David Murdoch