Created
December 28, 2017 20:16
-
-
Save andrzj/3cd3eb6245a67eec74a9432302504593 to your computer and use it in GitHub Desktop.
Ways to check if something is changed on your page (client side)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#form').data('serialize',$('#form').serialize()); // On load save form current state | |
$(window).bind('beforeunload', function(e){ | |
if($('#form').serialize()!=$('#form').data('serialize'))return true; | |
else e=null; // i.e; if form state change show box not. | |
}); | |
// ******* | |
var initial_form_state = $('#myform').serialize(); | |
$('#myform').submit(function(){ | |
initial_form_state = $('#myform').serialize(); | |
}); | |
$(window).bind('beforeunload', function(e) { | |
var form_state = $('#myform').serialize(); | |
if(initial_form_state != form_state){ | |
var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?"; | |
e.returnValue = message; // Cross-browser compatibility (src: MDN) | |
return message; | |
} | |
}); | |
// ******** | |
// You can use the following one-liner to always ask the user before leaving the page. | |
window.onbeforeunload = s => ""; | |
// To ask the user when something on the page has been modified, | |
window.onbeforeunload = s => modified ? "" : null; | |
/* Just set modified to true or false depending on the state of your application. | |
Some suggestions: Return a custom message rather than an empty string as some browsers will display it (e.g. Edge), | |
and return undefined rather than null as IE will print 'null' if modified is false. */ | |
// ******** | |
// to show the confirmation message just when I have unsaved data | |
window.onbeforeunload = function () { | |
if (isDirty) { | |
return "There are unsaved data."; | |
} | |
return undefined; | |
} | |
/* returning "undefined" will disable the confirmation | |
Note: returning "null" will not work with IE */ | |
// ************* | |
var unsaved = false; | |
$(":input").change(function () { | |
unsaved = true; | |
}); | |
function unloadPage() { | |
if (unsaved) { | |
alert("You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?"); | |
} | |
} | |
window.onbeforeunload = unloadPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment