window.onbeforeunload - Only show warning when not submitting form [duplicate] window.onbeforeunload - Only show warning when not submitting form [duplicate] javascript javascript

window.onbeforeunload - Only show warning when not submitting form [duplicate]


Using the form's submit event to set a flag might work for you.

 var formHasChanged = false; var submitted = false;$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {    formHasChanged = true;});$(document).ready(function () {    window.onbeforeunload = function (e) {        if (formHasChanged && !submitted) {            var message = "You have not saved your changes.", e = e || window.event;            if (e) {                e.returnValue = message;            }            return message;        }    } $("form").submit(function() {     submitted = true;     });});


you could use .on() to bind onbeforeunload and then use .off() to unbind it in form submission

$(document).ready(function () {    // Warning    $(window).on('beforeunload', function(){        return "Any changes will be lost";    });    // Form Submit    $(document).on("submit", "form", function(event){        // disable warning        $(window).off('beforeunload');    });}


You can handle the submit() event, which will occur only for your form submission.

Within that event, set your flag variable formHasChanged to false to allow the unload to proceed. Also, just a suggestion, but since the purpose of that flag variable will have changed, so you may want to rename it something like 'warnBeforeUnload'

$(document).submit(function(){    warnBeforeUnload = false;});