Display a warning that says "onbeforeunload" when you exit the page, except for the "Submit" button

I want to display a warning if the user finishes leaving the page containing the unsaved settings, but obviously not if they try to save these settings.

I think my understanding is wrong, as I thought the following should work, but it is not. Can someone tell me what I'm doing wrong? Thanks.

$('input[name="Submit"]').off('onbeforeunload'); window.onbeforeunload = function closeEditorWarning(){ /** Check to see if the settings warning is displayed */ if($('#unsaved-settings').css('display') !== 'none'){ bol_option_changed = true; } /** Display a warning if the user is trying to leave the page with unsaved settings */ if(bol_option_changed === true){ return ''; } }; 
+6
source share
3 answers

you can try: set the flag when you click the submit button and use this flag to check if the user clicked the sent or left the page halfway

Pseudocode:

 var submit_clicked = false; $('input[name="Submit"]').click(function(){ submit_clicked = true; }); window.onbeforeunload = function closeEditorWarning () { /** Check to see if the settings warning is displayed */ if(($('#unsaved-settings').css('display') !== 'none') && submit_clicked === false) { bol_option_changed = true; } /** Display a warning if the user is trying to leave the page with unsaved settings */ if(bol_option_changed === true){ return ''; } }; 
+3
source

you can use jquery.on () to set onbeforeunload and then use .off () in the form view

 // Warning $(window).on('beforeunload', function(){ return "Any changes will be lost"; }); // Form Submit $(document).on("submit", "form", function(event){ // disable unload warning $(window).off('beforeunload'); }); 
+7
source

I ran into this problem, so I would like to share my solution.

The Brent White solution does not work for me because I am using the jQuery-validation plugin. This means that if users provide invalid input, even after they click the submit button, they will still remain on the page. At this point, if they leave or refresh the page, a warning message will not be displayed.

 $(window).bind('beforeunload', function(evt) { var isSubmitButton = (evt.srcElement.activeElement.type === "submit"); var isModified = ($form.data("isModified") === true); if ( !isSubmitButton && isModified) { return "You need to save your changes before you leave the page"; } }); 
0
source

All Articles