I have this little piece of code:
This is what we use:
On the document ready we call the beforeunload function.
$(document).ready(function(){
$(window).bind("beforeunload", function(){ return(false); });
});
Before any submit or location.reload we unbind the variable.
$(window).unbind('beforeunload');
formXXX.submit();
$(window).unbind("beforeunload");
location.reload(true);
Looking for Detect onbeforeunload for ASP.NET web application well I was, I've to show warning message if some input control changes on the page using ASP.NET with Master Page and Content Pages. I'm using 3 content placeholders on the master page and the last one is after the form
<form runat="server" id="myForm">
so after the form closing tag and before the body closing tag used this script
<script>
var warnMessage = "Save your unsaved changes before leaving this page!";
$("input").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$("select").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$(function () {
$('button[type=submit]').click(function (e) {
window.onbeforeunload = null;
});
});
</script>
beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively
so I got it working like this bind and unbind didn't work out for me also With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions.
Use
$('form').submit(function () {
window.onbeforeunload = null;
});
Make sure you have this before you main submit function! (if any)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>
<script type="text/javascript">
$(function() {
$('#form_verify').dirtyForms();
})
</script>
<title></title>
<body>
<form id="form_verify" action="a.php" method="POST">
Firt Name <input type="text">
Last Name <input type="file">
<input type="submit">
</form>
Call unbind using the beforeunload
event handler:
$('form#someForm').submit(function() {
$(window).unbind('beforeunload');
});
To prevent the form from being submitted, add the following line:
return false;
if you're using bind then use this:
$('form').submit(function () {
$(window).unbind('beforeunload');
});
This will be good for all form submit.