Alert for unsaved changes in form

前端 未结 7 1898
谎友^
谎友^ 2020-11-30 18:47

I want to write Jquery code in master file, so that if there if user changes page and there is any unsaved changes user should get alert. I got one answer from this: link

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 19:11

    A version that use serialization of the form :

    Execute this code, when dom ready :

    // Store form state at page load
    var initial_form_state = $('#myform').serialize();
    
    // Store form state after form submit
    $('#myform').submit(function(){
      initial_form_state = $('#myform').serialize();
    });
    
    // Check form changes before leaving the page and warn user if needed
    $(window).bind('beforeunload', function(e) {
      var form_state = $('#myform').serialize();
      if(initial_form_state != form_state){
        var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
        e.returnValue = message; // Cross-browser compatibility (src: MDN)
        return message;
      }
    });
    

    If the user change a field then manually rollback, no warn is displayed

提交回复
热议问题