1 3 Votes

jQuery: Show Window.OnBeforeUnload Warning except Submit Button was clicked

Tip by Stefan Trost | 07/10/2016 at 20:17

With Window.OnBeforeUnload it is possible to show a warning to the user when he is about to leave the page. Window.OnBeforeUnload becomes active when trying to close the corresponding tab or the whole browser. However, it also becomes active when only clicking the submit button of the form - a case in which there is no risk that the user input could get lost.

This is the reason why I want to show you a solution with which you can ensure that the Window.OnBeforeUnload is only displayed if the submit button was not pressed:

var submitted = false;

$(document).ready(function() {
  $("form").submit(function() {
    submitted = true;
  });

  window.onbeforeunload = function () {
    if (!submitted) {
      return 'Do you really want to leave the page?';
    }
  }
});

The variable "submitted" should indicate whether the submit button was already clicked. Correspondingly, first, we are setting this variable to "false".

In the moment when clicking the submit button of our form, we are setting "submitted" to "true" to be able to show the wanting in our window.onbeforeunload function only in the opposite case.

ReplyPositiveNegative

About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.