Confirm to leave the page when editing a form with jQuery

前端 未结 5 2096
无人共我
无人共我 2020-12-05 00:50

I am coding a form and I need a function like stackoverflow have: \"You have started writing or editing a post.\".

I\'ve looked through the code of stackoverflow to

5条回答
  •  鱼传尺愫
    2020-12-05 01:45

    Based on Wasim A. answer. That code snipped looks great, but if I clicked to submit button I have an notification too. I think this is better:

    $(document).ready(function() {
        let form = $('#form');
        form.data('serialize', form.serialize());
        
        // if submit clicked - pass user to save form
        form.find('submit').on('click', function () {
            $(window).off('beforeunload');
        });
    });
    
    
    
      // On load save form current state
    
    $(window).bind('beforeunload', function(e){
        let form = $('#form');
        if(form.serialize() !== form.data('serialize')) {
          return true;
        } else {
        // i.e; if form state change show box not.
          e=null;
        }
    });

提交回复
热议问题