How To Prevent "Are You Sure You Want To Navigate Away From This Page?" Alert On Form Submission?
Solution 1:
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
With JQuery this stuff is pretty easy to do. Since you can bind to sets.
Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.
To make this work in Chrome and Safari, you would have to do it like this
window.onbeforeunload = function (e) {
e = e || window.event;
var msg = "Sure you want to leave?";
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
};
This is the general rule in reference
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE<8 and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Chrome, Safari, IE8+ and Opera 12+
return 'Any string';
};
reference: https://developer.mozilla.org/en/DOM/window.onbeforeunload
Solution 2:
Try this:
<form action="c.html" onsubmit="window.onbeforeunload=function(){}">
Solution 3:
Try this:
$(window).bind("beforeUnload", verify);
$("form").submit(function (){
$(window).unbind("beforeUnload");
};
Solution 4:
I added another bit to the function:
$('#submitButton').click(function () {
isDirty = false;
});
Just so the form doesn't ask for validation when you want to submit it :)
I hope this helps
Note: You could also do something like $("input[type=submit]") if you don't like to depend on a common naming (else your submit button needs to be called submitButton)
Post a Comment for "How To Prevent "Are You Sure You Want To Navigate Away From This Page?" Alert On Form Submission?"