Repository navigation
Expand file tree
/
Copy pathformhandler.js
More file actions
128 lines (105 loc) · 3.38 KB
/
Copy pathformhandler.js
File metadata and controls
128 lines (105 loc) · 3.38 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
;(function(jQuery, window, document)
{
var pluginName = 'formHandler',
defaults = {
loadingIndicator: false,
hideValidationMessages: false,
actionUrl: '',
useAjax: true,
ajaxOptions: {}
};
function FormHandler(element, options)
{
this.$element = element;
this.options = jQuery.extend({}, defaults, options);
this.response = jQuery.Deferred();
this.init()
}
// Class
FormHandler.prototype = {
init: function()
{
this._addEvents();
// Add action url if nothing is definied
if (this.options.actionUrl == '')
{
this.options.actionUrl = this.$element.attr('action');
}
// Hide validation messages?
if (this.options.hideValidationMessages)
{
this.$element.addClass('hide-validation-messages');
}
},
send: function()
{
var q = jQuery.Deferred();
this.isValid().then(function(formdata)
{
if (this.options.useAjax)
{
var ajaxOptions = jQuery.extend({}, this.options.ajaxOptions, {
url: this.$element.attr('action'),
method: this.$element.attr('method'),
cache: false,
data: formdata
});
jQuery.ajax(ajaxOptions)
.done(function(response)
{
q.resolve(response);
}.bind(this))
.fail(function(response)
{
q.reject(jQuery.parseJSON(response.responseText));
}.bind(this));
}
else
{
this.$element.submit();
}
}.bind(this));
return q.promise();
},
isValid: function()
{
var d = jQuery.Deferred(),
isValid = this.$element.isValid();
(isValid) ? d.resolve(this.getFormdate()) : d.reject();
return d.promise();
},
getFormdate: function()
{
var formdata = {};
this.$element.find('input, textarea').each(function(ix, el)
{
var $el = $(el);
switch ($el.prop('nodeName').toLowerCase())
{
case 'checkbox':
formdata[$el.attr('name')] = $el.prop('checked');
default:
formdata[$el.attr('name')] = $el.val();
}
});
return formdata;
},
getSubmitButton: function()
{
return this.$element.find('button[type="submit"]');
},
_addEvents: function()
{
jQuery.validate({ form: this.$element });
}
};
// Plugin
$.fn[pluginName] = function(options)
{
if (!$(this).data(pluginName))
{
$(this).data(pluginName, new FormHandler(this, options));
}
return $(this).data(pluginName);
};
})(jQuery, window, document);