forked from MrSwitch/hello.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello.form.js
More file actions
108 lines (86 loc) · 2.64 KB
/
hello.form.js
File metadata and controls
108 lines (86 loc) · 2.64 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
// EXTRA: Convert FormElement to JSON for POSTing
// Wrappers to add additional functionality to existing functions
(function(hello) {
// Copy original function
var api = hello.api;
var utils = hello.utils;
utils.extend(utils, {
// DataToJSON
// This takes a FormElement|NodeList|InputElement|MixedObjects and convers the data object to JSON.
dataToJSON: function(p) {
var _this = this;
var w = window;
var data = p.data;
// Is data a form object
if (_this.domInstance('form', data)) {
data = _this.nodeListToJSON(data.elements);
}
else if ('NodeList' in w && data instanceof NodeList) {
data = _this.nodeListToJSON(data);
}
else if (_this.domInstance('input', data)) {
data = _this.nodeListToJSON([data]);
}
// Is data a blob, File, FileList?
if (('File' in w && data instanceof w.File) ||
('Blob' in w && data instanceof w.Blob) ||
('FileList' in w && data instanceof w.FileList)) {
data = {file: data};
}
// Loop through data if it's not form data it must now be a JSON object
if (!('FormData' in w && data instanceof w.FormData)) {
for (var x in data) if (data.hasOwnProperty(x)) {
if ('FileList' in w && data[x] instanceof w.FileList) {
if (data[x].length === 1) {
data[x] = data[x][0];
}
}
else if (_this.domInstance('input', data[x]) && data[x].type === 'file') {
continue;
}
else if (_this.domInstance('input', data[x]) ||
_this.domInstance('select', data[x]) ||
_this.domInstance('textArea', data[x])) {
data[x] = data[x].value;
}
else if (_this.domInstance(null, data[x])) {
data[x] = data[x].innerHTML || data[x].innerText;
}
}
}
p.data = data;
return data;
},
// NodeListToJSON
// Given a list of elements extrapolate their values and return as a json object
nodeListToJSON: function(nodelist) {
var json = {};
// Create a data string
for (var i = 0; i < nodelist.length; i++) {
var input = nodelist[i];
// If the name of the input is empty or diabled, dont add it.
if (input.disabled || !input.name) {
continue;
}
// Is this a file, does the browser not support 'files' and 'FormData'?
if (input.type === 'file') {
json[input.name] = input;
}
else {
json[input.name] = input.value || input.innerHTML;
}
}
return json;
}
});
// Replace it
hello.api = function() {
// Get arguments
var p = utils.args({path: 's!', method: 's', data:'o', timeout: 'i', callback: 'f'}, arguments);
// Change for into a data object
if (p.data) {
utils.dataToJSON(p);
}
return api.call(this, p);
};
})(hello);