9

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?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
ingh.am
  • 25,981
  • 43
  • 130
  • 177

2 Answers2

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

archil
  • 39,013
  • 7
  • 65
  • 82
5

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!

Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222