Code
<script> 
  
  var somethingChanged=false;
   $("form:not(#loginForm)").on("change", function(e){ //This function detects any changes except for on the login form
       if (!$(e.target).is('#id')) { //For all changes except for the field "id", the parameter that something changed is set. You may comment this out if not needed
         somethingChanged = true;
      }
   });
   
   $.fn.hasAnyClass = function() { //This function can deal with a number of classes entered below that will be excluded from the "are you sure you want to leave this page" notification
    for (var i = 0; i < arguments.length; i++) {
        if (this.hasClass(arguments[i])) {
            return true;
        }
    }
    return false;
   }
   
  window.onload = function() {
  window.addEventListener("beforeunload", function (e) {
        if (!$(document.activeElement).hasAnyClass('waves-button-input', 'form-button') //if the element that would trigger beforeunload has the mentioned classes, the dialog shown
            && !$(document.activeElement).parent().hasAnyClass('nav_item') //if the element has the mentioned parent class, the dialog won't be triggered (useful for Multi Page navigation that don't have a distinct own class)
            && somethingChanged) { //only if the form has changed the dialog will be triggered
                var confirmationMessage = 'It looks like you have been editing something. '
                                        + 'If you leave before saving, your changes will be lost.';
                (e || window.event).returnValue = confirmationMessage; //Gecko + IE
                return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
            }
        return undefined;
    });
 };
 
/*
 $(window).on('load', function() { //used for debugging
    console.log(somethingChanged);
})
*/
</script>





  • No labels