-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformwatcher.js
More file actions
109 lines (98 loc) · 3.77 KB
/
formwatcher.js
File metadata and controls
109 lines (98 loc) · 3.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* jQuery Form Watcher - v1.0.0
*
* Made by Christopher Smoak
* Under LGPLv3 License
*/
;(function( $ ) {
$.fn.formWatcher = function( options )
{
// allow user to specify message
var forms = [],
settings = $.extend({
message: 'Your changes have not been saved. Are you sure you want to continue?',
onChange: function(form, difference) {}
}, options);
// watch every form
this.filter("form").each(function()
{
var form = $(this);
// allow message to be overwritten by data attribute
if (form.attr('data-formwatcher-message'))
{
settings.message = form.attr('data-formwatcher-message');
}
// attach original form data to form
form.data('submitting', false);
form.data('original_data', form.serialize());
form.data('original_data_array', form.serializeArray());
// update submitting var to allow form to submit
// without throwing onbeforeunload message
form
.on('change', function(event)
{
var originalData = form.data('original_data_array'),
currentData = form.serializeArray(),
diffs = [];
// get data diff
$.each(originalData, function(index, originalField)
{
$.each(currentData, function(index2, currentField)
{
if (originalField.name == currentField.name
&& originalField.value != currentField.value)
{
var diff = {
field: originalField.name,
oldValue: originalField.value,
newValue: currentField.value
}
diffs.push(diff);
}
});
});
// call on change
settings.onChange.call(this, form, diffs);
})
.on('submit', function(event)
{
form.data('submitting', true);
});
// keep track of all forms
forms.push(form);
});
// if we have forms check all forms for changes
if (forms.length > 0)
{
// stop page reload unless we are submitting
window.onbeforeunload = function(event)
{
var anyChanged = false, anySubmitting = false,
anotherFormChangedAndNotBeingSubmitted = false;
$.each(forms, function(index, form)
{
if (form.serialize() != form.data('original_data'))
{
anyChanged = true;
}
if (form.data('submitting'))
{
anySubmitting = true;
}
// ther is another form on the page that has been changed
if (form.serialize() != form.data('original_data') && !form.data('submitting'))
{
anotherFormChangedAndNotBeingSubmitted = true;
}
});
// thow message if any change & not submitting
if ((anyChanged && !anySubmitting)
|| anotherFormChangedAndNotBeingSubmitted)
{
return settings.message;
}
}
}
return this;
};
}(jQuery));