Confirm to leave the page when editing a form with jQuery

You can do this using window.onbeforeunload like this:

window.onbeforeunload = function() {
    return 'Are you sure you want to navigate away from this page?';
};

So in your code, you would put that inside the success callback of your $.ajax call.

To unset the confirmation, you can do this:

window.onbeforeunload = null;

Also, see this answer: How can I override the OnBeforeUnload dialog and replace it with my own?


This is how in JQuery

$('#form').data('serialize',$('#form').serialize());
  // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null;
    // i.e; if form state change show box not.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

Tags:

Jquery