Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  181] [ 4]  / answers: 1 / hits: 40321  / 12 Years ago, wed, august 1, 2012, 12:00:00

I am using window.onbeforeunload to prevent the user from navigating away after changing values on a form. This is working fine, except it also shows the warning when the user submits the form (not desired).



How can I do this without showing the warning when the form submits?



Current code:



var formHasChanged = 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) {
var message = You have not saved your changes., e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
});

More From » jquery

 Answers
45

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;
});
});

[#83915] Tuesday, July 31, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
demondp

Total Points: 154
Total Questions: 97
Total Answers: 99

Location: Mali
Member since Thu, Jul 9, 2020
4 Years ago
;