Skip to content

Instantly share code, notes, and snippets.

@2ndkauboy
Created August 25, 2015 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2ndkauboy/b3015044becd97106b41 to your computer and use it in GitHub Desktop.
Save 2ndkauboy/b3015044becd97106b41 to your computer and use it in GitHub Desktop.
A jQuery plugin to prevent a user to navigate off of a page without saving the form data
;(function($) {
var settings = {
'warnings' : {
'unsavedform': 'ACHTUNG: Ihre Änderungen wurden noch nicht gespeichert!\n\nDrücken Sie "Auf dieser Seite bleiben" und speichern Sie die Daten! Wenn Sie auf "Diese Seite verlassen" klicken gehen Ihre Änderungen verloren!',
'unsavedtab': 'ACHTUNG: Ihre Änderungen wurden noch nicht gespeichert!\n\nDrücken Sie "Abbrechen" und speichern Sie die Daten! Wenn Sie auf "OK" klicken gehen Ihre Änderungen verloren!'
},
'submitted' : false
};
var methods = {
init : function(options){
if(options){
$.extend(settings, options);
}
// reference to the form
settings.form = this;
// reference to the form DOM element
var formNode = settings.form.get( 0 );
// initial form data on page load
settings.formData = methods.getFormData();
// check if form has been submitted to avoid false alarms
$(this).submit(function(){
if( ! methods.hasFormValidation() || formNode.hasAttribute( 'novalidate' ) || formNode.checkValidity()){
settings.submitted = true;
}
});
// show a message on unload if the form data has been changes but not been saved before
$(window).on('beforeunload', function(){
return methods.checkFormData();
});
},
checkFormData : function(){
if(!settings.submitted && JSON.stringify(settings.formData) != JSON.stringify(methods.getFormData())){
return settings.warnings.unsavedform;
}
},
getFormData : function(){
var formArray = $(settings.form).serializeArray();
var formValues = [];
$.each(formArray, function(i, elm){
if(settings.excludedFields){
if($.inArray(elm.name, settings.excludedFields) == -1){
formValues.push(elm);
}
} else {
formValues.push(elm);
}
});
return formValues;
},
hasFormValidation : function (){
return ( typeof document.createElement( 'input' ).checkValidity == 'function' );
}
};
$.fn.formrescuer = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.formrescuer' );
}
};
})(jQuery);
@2ndkauboy
Copy link
Author

Just select the form to rescue and call the plugin on it (you may exclude some fields to be checked):

var formRescuer = jQuery('#form').formrescuer({
    excludedFields: ['spam_protect']
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment