Milano
Milano

Reputation: 18725

window.onbeforeunload confirmation if submit not clicked

I'm working on a quiz. The page can't be closed before submitting the form, otherwise all data will be lost. This can be done using:

window.onbeforeunload = function () {
    return "Are you sure?"
}

But what if I don't want to trigger this alert if user clicked on "Submit"? I tried the code below but it doesn't work at all - it doesn't show the alert even if window is being closed.

var clicked_submit = false;
$(document).ready(function () {
      $('#submit-button').click(function () {
          clicked_submit = true;
      });

      window.onbeforeunload = function () {
          if (clicked_submit){

          } else {
              return 'Are you sure?'
          }
      }
  });

Upvotes: 0

Views: 411

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16069

One simple solution is to just return the function without any value.

var clicked_submit = false;
$(document).ready(function () {
      $('#submit-button').click(function () {
          clicked_submit = true;
      });
      window.onbeforeunload = function () {
         if (clicked_submit){
             return; // equal to return undefined;
         } else {
             return 'Are you sure?'
         }
     }
});

A cleaner solution would be, to simply set the window.onbeforeunload to null.

var clicked_submit = false;
$(document).ready(function () {
      $('#submit-button').click(function () {
          clicked_submit = true;
      });
      if(!clicked_submit) {
          window.onbeforeunload = function () {
              return 'Are you sure?'
          }
      } else {
          window.onbeforeunload = null;
      }
});

Upvotes: 1

Related Questions