Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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."; };
like image 704
Yamaha32088 Avatar asked Sep 14 '25 03:09

Yamaha32088


2 Answers

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>
like image 108
Simon Soriano Avatar answered Sep 16 '25 16:09

Simon Soriano


i think you have to write that function, 'function() { return "Your work will be lost."; };' inside your onClick event of back button. And remove that line 'window.onbeforeunload = function() { return "Your work will be lost."; };'. I think, it will work fine...

like image 32
DMajumdar Avatar answered Sep 16 '25 17:09

DMajumdar