views:

1022

answers:

3

Hey guys, What I'm trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.

I've managed to get the OnBeforeUnload() dialog to pop-up... but I don't want it to be displayed at all if the user hasn't modified any field values. For this, I'm using this hidden input field called is_modified that starts with a default value of false and flips to true when any field is edited.

I tried to bind the change event to this is_modified field to try and detect for value change... and only then activate OnBeforeUnload.

$( '#is_modified' ).change( function() {
    if( $( '#is_modified' ).val() == 'true' )
     window.onbeforeunload = function() { return "You have unsaved changes."; }
});

But from what I figure is that the change() event works only after these 3 steps - a field receives focus, a value is changed and the field looses focus. In case of the hidden input field, I'm not sure how this receiving and loosing focus part works! Hence, the onbeforeunload function is never being activated.

Can anyone suggest a way to maintain a trigger over is_modified?

Thanks, m^e

A: 

Try your logic in a different manner. Meaning, put the logic for checking the value of the input field in your onbeforeunload method.

window.onbeforeunload = function () { 
    if ($("#is_modified").val() == 'true') { 
     return "You have unsaved changes."; 
    } else { 
     return true; // I think true is the proper value here 
    } 
};
Jordan S. Jones
"true" is not the proper value. In some browsers (At least Firefox, perhaps more) returning "null" will cancel the dialog.Howerver, in IE, I could not find a way to cancel the dialog from within the handler. The only thing that worked for me was to remove the handler entirely beforehand (ie, "window.beforeunload = null"), as in Bryan Larsen's answer.
Jason Creighton
Fair enough. Sadly, I didn't thoroughly test my solution before I answered. :(
Jordan S. Jones
A: 

why not have the onbeforeunload call a function that checks if the values have changed, and if so return the "unsaved changes" confirm?

Jonathan Fingland
+3  A: 

We just use Window.onbeforeunload as our "changed" flag. Here's what we're doing, (using lowpro):

Event.addBehavior({
  "input[type=radio]:change,input[type=text]:change,input[type=checkbox]:change,select:change": function(ev) {
       window.onbeforeunload = confirmLeave;
  }
  ".button.submit-button:click": function(ev) {
       window.onbeforeunload = null;
  },
});


function confirmLeave(){
    return "Changes to this form have not been saved. If you leave, your changes will be lost."  
}
Bryan Larsen