1

i am working on online quiz system with php and mysql which displays one question at a time and this question is submitted it displays the second one and so on. I want to prevent the student student from leaving the exam page by clicking back button or close tab. I tried the following code:

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

};

It really alerts the student when he clicks the back button or close the page but it also gives an alert when the student is submitting the first question to display the second one. Does anyone have any idea how to solve this problem???

aaa ggg
  • 7
  • 2
  • Simply disable the event handler before submit. So subscribe event handler for submit, remove the onbeforeunload, then continue with normal submit flow. – ficuscr Sep 13 '17 at 19:32

1 Answers1

0
  if (e) {
    e.returnValue = message;
  }

You will have to validate the event. Have an Id to the submit/next button and try to validate the event. Suppose you have an id called "submit" to the submit button

if (e.target.id !== 'submit') {
    e.returnValue = message;
  }
Brr Switch
  • 974
  • 1
  • 9
  • 21