4

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."; };
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • Change your method to have it check if the cause of leaving the page was the form. If it was from the form, return nothing rather than a string. – Kevin B Feb 12 '14 at 21:19
  • You'll need to bind your submit button to a javascript function and then in the function you can write logic to show the alert...For your help you can see this ..http://stackoverflow.com/questions/1947263/using-an-html-button-to-call-a-javascript-function – tgpatel Feb 12 '14 at 21:59

4 Answers4

7

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>
Simon Soriano
  • 803
  • 12
  • 19
1

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...

DMajumdar
  • 170
  • 1
  • 8
0

window.onbeforeunload will get triggered even on normal tab or link clicks in addition to the browser's button clicks. I didn't find any trigger exclusive to the browser's back or forward clicks.

MullaBihari
  • 61
  • 1
  • 3
0

After trying so many complex way, I get this solution.

    window.onbeforeunload = function () {
        return 'Are you sure? Your work will be lost.';
    };

    $(document).on("submit", "form", function () {
        window.onbeforeunload = null;
    });
MD Ashik
  • 9,117
  • 10
  • 52
  • 59