I wish to display a warning if a user attepmts to leave a page that contains unsaved settings, but obviously not if they are attempting to save those settings.
I guess my understanding is wrong, as I thought the below should work, but it does not. Can somebody tell me what I am 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 '';
}
};
preventDefault(); event. returnValue = 'You have unsaved changes. '; } }); } attached = true; }); }(jQuery)); This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
To make a warning alert or confirm dialog display when the user reloads the page or closes a tab using javascript, we can use window. addEventListener() and beforeunload events like the script above.
Purpose: The beforeunload event triggers right before unloading of the window has begun. unload would trigger while unloading of the window is taking place.
you could use jquery .on() to set onbeforeunload and then use .off() in form submission
// 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');
});
you can try this: set a flag when submit button is clicked and use this flag to check if the user has clicked submitted or leaving the page halfway
Pseudo code:
var submit_clicked = false;
$('input[type="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 '';
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With