简体   繁体   中英

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?'
          }
      }
  });

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;
      }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM