A warning has been added when the user clicks the back button, but now I want to delete it when I submit the form

I have a very long survey, and I want the user to not press the back button and not lose all his data. So far I have a warning saying that they will lose all the data, but when they submit the form for processing the page, it will appear with a warning. Is there a way to turn off the alert only when they click the submit button? This is the method I use to create an alert:

window.onbeforeunload = function() { return "Your work will be lost."; };
+3
source share
3 answers

You can set the beforeunload listener as follows:

var preventUser = function() {
    return "Your work will be lost";
}
window.addEventListener('beforeunload',preventUser);

, , :

function onSubmitForm(){
    window.removeEventListener('beforeunload',preventUser);
}

:

<button onclick="onSubmitForm()">Submit Form</button>
+6

, , 'function() {return " ."; };" onClick. 'window.onbeforeunload = function() {return " ."; };". , ...

+1

window.onbeforeunload will be activated even with the usual tab or click on the link in addition to the clicks of the browser button. I did not find a trigger exclusive to the back or direct click of the browser.

0
source

All Articles