15 Votes

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

Tip by Stefan Trost | 2016-10-07 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.

00 Votes

Uncaught ReferenceError: $ is not defined

$(document).ready(function() {
2022-11-05 at 14:21

ReplyPositive Negative
00 Votes

When you get that error, you have forgotten to include the jQuery framework on which the code above is based. As you can see, it's a jQuery solution here, so you have to include it.
2022-11-05 at 15:31

Positive Negative

About the Author

AvatarYou 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


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.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.