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

javascript - Stop user from leaving web page, except for when submitting form - Stack Overflow

programmeradmin3浏览0评论

To stop the user from leaving my page, I'm using this javascript:

window.onbeforeunload = function()
{
  if($('textarea#usermessage').val() != '')
  {
    return "You have started writing a message.";
  }
};

This shows a message warning the user not to leave the page because they've started writing a message but not submitted. This shows up to save the user from losing this data.

Now, how can I stop this message from showing up when the form is submitted?

To stop the user from leaving my page, I'm using this javascript:

window.onbeforeunload = function()
{
  if($('textarea#usermessage').val() != '')
  {
    return "You have started writing a message.";
  }
};

This shows a message warning the user not to leave the page because they've started writing a message but not submitted. This shows up to save the user from losing this data.

Now, how can I stop this message from showing up when the form is submitted?

Share Improve this question edited Jul 8, 2011 at 8:27 Paul D. Waite 98.8k57 gold badges202 silver badges271 bronze badges asked Jul 8, 2011 at 8:18 ingh.amingh.am 26.8k43 gold badges132 silver badges179 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9
function handleWindowLeaving(message, form) {
    $(window).bind('beforeunload', function (event) {
        return message;
    });
    $(form).bind('submit', function () {
        $(window).unbind('beforeunload');
    });
};

when calling this, pass your message and the form reference, and it will automatically remove onbeforeunload when submitting the form. Otherwise, show message to user

Set a flag in your form's submit handler; check whether the flag is set in your unload handler. If it is - voila, it's a form submit!

发布评论

评论列表(0)

  1. 暂无评论