how to disable onbeforeunload on form submission

Shiv Om Sharma
Shiv Om Sharma used Ask the Experts™
on
I want to implement onbeforeunload  on tab close but want to disable  onbeforeunload  on form submission :

$('input[type="submit"]').on("click", function (e) {
      window.onbeforeunload = function() {};
      $(window).unbind('beforeunload');
});
does not work.
it still shows leave confirmation message
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Owner (Aidellio)
Most Valuable Expert 2015
Commented:
$('input[type="submit"]').on("click", function (e) {
    // set a flag
    window.form_submit = true;
});

then in your onbeforeunload

$(window).on("beforeunload", function (e) {
    if (!form_submit) {
        // do what you want in the beforeunload
    }
});
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Building on Rob's post, here is some working code
HTML
  <p>Click this link to see the message <a href="http://www.experts-exchange.com">EE</a></p>
  <p>Submit the form to see the beforeunload is bypassed</p>
  <form action="reflect.php">
    <input type="submit">
  </form>

Open in new window

jQuery / JavaScript
<script>
var message = true;
$(function() {
  $('form').submit(function() {
    message = false;
  });
});
window.onbeforeunload = function(e) {
  if (message) {
    var dialogText = 'Dialog text here';
    e.returnValue = dialogText;
    return dialogText;
  }
}
</script>

Open in new window

Working sample here

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial