-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautosave.js
52 lines (52 loc) · 1.6 KB
/
autosave.js
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
// jQuery plugin to save individual form fields each time something changes.
// Usage: `$('#MyForm').autosave(url, options);`
// where `url` defaults to form.method
// and `options` defaults to $.fn.autosave.defaultOptions
// (UNTESTED)
;(function($) {
$.fn.autosave = function(url, options) {
// build options based on defaultOptions and passed options
options = $.extend({}, $.fn.autosave.defaultOptions, options || {});
// `this` is the jQuery collection
return this.each(function() {
// `this` is the <form> element
if (!this.elements) {
return;
}
url = url || this.action;
options.method = options.method || this.method;
var $idElement = $(options.idElement || this.elements[options.idElementName]);
if ($idElement.length == 0) {
return;
}
$(this.elements).change(function() {
// `this` is the input element that changed
var queryString =
options.idField + '=' + encodeURIComponent($idElement.val()) +
options.columnField + '=' + encodeURIComponent(this.name) +
options.valueField + '=' + encodeURIComponent($(this).val())
;
if (options.useImage) {
var img = new Image(url + '?' + queryString);
}
else {
$.ajax($.extend({
url: url,
method: options.method,
data: queryString
}, options.ajaxOptions));
}
});
});
};
$.fn.autosave.defaultOptions = {
idElement: null,
idElementName: 'id',
idField: 'id',
columnField: 'column',
valueField: 'value',
method: null,
ajaxOptions: {},
useImage: false
};
})(jQuery);