Created
June 4, 2011 03:50
-
-
Save brainlid/1007552 to your computer and use it in GitHub Desktop.
Handle "Your changes will be lost" prompt when navigating away from a changed page.
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
| // To activate this, add the class "confirm_discard" to your form. If | |
| // you change any value on the form, it will set the onbeforeunload. | |
| // When you send the submit event (AJAX or normal GET / POST), it | |
| // clears it. Since it uses delegate, there's no need to run | |
| // additional setup code after an ajax call has loaded a form on the | |
| // page. | |
| // This won't interfere with any other custom beforeunload event | |
| // handlers you may have. | |
| // This works with multiple forms on a page as well. | |
| // To force form to be marked 'dirty', you can $('form').data('data-changed',true); | |
| // To force clear the changed flag, you can $('form').data('data-changed',false); | |
| // To test if a form is dirty, you can call $('form').data('data-changed). | |
| $('body').delegate('form.confirm_discard input, form.confirm_discard select, form.confirm_discard textarea','change',function(){ | |
| $(this).closest('form.confirm_discard').data('data-changed', true); | |
| }); | |
| $('body').delegate('form.confirm_discard','submit',function(){ | |
| $(this).closest('form.confirm_discard').data('data-changed', false); | |
| }); | |
| $(window).bind('beforeunload',function(){ | |
| var foundChange = false; | |
| $('form.confirm_discard').each(function(){ | |
| if ($(this).data('data-changed')){ | |
| foundChange = true; | |
| } | |
| }); | |
| if (foundChange){ | |
| return "If you proceed, your changes will be lost"; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment