Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger onbeforeunload if form is not submitted

I've got a form which is being submitted via PHP with 3 submit actions:

  • Save and Continue
  • Save and Exit
  • Exit without Saving

I'd like to trigger an "OnBeforeUnload" alert to display if the user DOES NOT click on any of the form actions to advise them that they're leaving the page, and their changes may not be saved.

I've tried the following code but it seems as though the unbeforeunload is being triggered before my click event. Any suggestions on how best to achieve this?

$buttonpressed = false;
$j(".Actions input").click(function(){
    $buttonpressed = true;                                  
});

if(!$buttonpressed){
    window.onbeforeunload = function(){
        return "Your changes may not be saved.";
    }
}
like image 837
pingu Avatar asked Dec 03 '22 04:12

pingu


1 Answers

You need to do the check inside the handler, like this:

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

Currently it's binding window.onbeforeunload when your code is run because $buttonpressed is false when it runs...it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a bit simpler, like this:

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

This just removes the handler on click instead. A more appropriate event to handle other submit cases would be to attach to the submit event, like this:

$j(".myForm").submit(function(){
    window.onbeforeunload = null;
});
like image 126
Nick Craver Avatar answered Dec 16 '22 13:12

Nick Craver