简体   繁体   中英

jQuery: Confirmation dialog before leaving a page while in editing mode

I try to appear a message when the user edit some field and try to go to another page or click close to the page

message appear

This page is asking you to confirm that you want to leave - data you have entered may not be saved.

I use this code :

$('#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.
});

This code works only when the user try to edit something if not I can close the page and thats what I want.

The problem is that the message appear also when I submit the form

When I try to click the button submit the message appear also

This page is asking you to confirm that you want to leave - data you have entered may not be saved.

How to prevent to show that message when I click the submit button ??!!

Save the listener in a variable and remove it on submit

 const onBeforeUnloadListener function(e){ if($('#form').serialize()!=$('#form').data('serialize'))return true; else e=null; // ie; if form state change show box not. } $(window).bind('beforeunload', onBeforeUnloadListener); $('#form').on('submit', function() { $(window).unbind('beforeunload', onBeforeUnloadListener) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM