admin管理员组

文章数量:1300200

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."; };

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."; };
Share Improve this question asked Feb 12, 2014 at 21:17 Yamaha32088Yamaha32088 4,16310 gold badges53 silver badges105 bronze badges 2
  • 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 Commented Feb 12, 2014 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 ..stackoverflow./questions/1947263/… – tgpatel Commented Feb 12, 2014 at 21:59
Add a ment  | 

4 Answers 4

Reset to default 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>

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

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.

After trying so many plex 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;
    });

本文标签: