最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger onbeforeunload if form is not submitted - Stack Overflow

programmeradmin1浏览0评论

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

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.";
    }
}
Share Improve this question asked Nov 13, 2010 at 13:14 pingupingu 6241 gold badge10 silver badges24 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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;
});
发布评论

评论列表(0)

  1. 暂无评论