Trigger onbeforeunload if form is not submitted

流过昼夜 提交于 2019-12-18 17:14:00

问题


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.";
    }
}

回答1:


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;
});


来源:https://stackoverflow.com/questions/4172671/trigger-onbeforeunload-if-form-is-not-submitted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!