Added alert for when user clicks back button but now I want to remove it when submitting the form

forms, html, javascript, jquery

Solution

You can set the beforeunload listener in this way:

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

And then, when the user submit the form, you can remove the listener in this way:

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

For example:

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

Problem

I have a very long survey and I want to prevent the user from clicking the back button and losing all of their data. So far I have an alert that tells them they will lose all the data but when they submit the form to process the page it will pop up with the alert. Is there a way I can disable the alert only when they press the submit button? This is the method I am using to create the alert: ``` window.onbeforeunload = function() { return "Your work will be lost."; }; ```

Original source

Related problems