问题
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 '';
}
};
回答1:
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[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 '';
}
};
回答2:
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');
});
回答3:
I encountered this problem so I would like to share my solution.
Brent White's solution does not work for me because I use the jQuery-validation plugin. It means that if the users provide invalid input, even after they click the submit button, they will still stay at the page. At this moment, if they leave or refresh the page, the alert message will not shown.
$(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";
}
});
回答4:
Here is the perfect answer for your question.
document.querySelector('.send').addEventListener("click", function(){ // put a class="send" in submit button
window.btn_clicked = true; // if it is click onbeforeunload will not add dialog anymore
});
window.onbeforeunload = function(){
if(!window.btn_clicked){
var lot = $('#lot_no').val(); //getting values from form
if(!lot == ''){ //checking if it is not empty
return 'Changes you made not be saved!';
}
}
};
来源:https://stackoverflow.com/questions/14341208/display-a-warning-with-onbeforeunload-when-leaving-a-page-except-if-submit