Onbeforeunload trigger if the form is not submitted

I have a form that submits via PHP with 3 submit actions:

  • Save and continue
  • Save and exit
  • Exit without saving

I would like to trigger an OnBeforeUnload warning to display if the user does NOT click on any actions in the form to inform them that they are leaving the page and their changes cannot be saved.

I tried the following code, but it seems that before my click event, unbeforeunload is fired. Any suggestions on how to best achieve this?

$buttonpressed = false; $j(".Actions input").click(function(){ $buttonpressed = true; }); if(!$buttonpressed){ window.onbeforeunload = function(){ return "Your changes may not be saved."; } } 
+4
source share
1 answer

You need to perform a check inside the handler, for example:

 window.onbeforeunload = function(){ if(!$buttonpressed){ return "Your changes may not be saved."; } } 

It currently binds window.onbeforeunload when your code is running, because $buttonpressed is false when it starts ... it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a little easier, for example:

 window.onbeforeunload = function(){ return "Your changes may not be saved."; } $j(".Actions input").click(function(){ window.onbeforeunload = null; }); 

It just removes the handler on click . A more appropriate event to handle other dispatch cases would be to attach to the submit event, for example:

 $j(".myForm").submit(function(){ window.onbeforeunload = null; }); 
+18
source

All Articles