-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
75 lines (61 loc) · 1.88 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*jshint maxcomplexity: 10*/
module.exports = FormData
//TODO: Massive spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constructing-form-data-set
function FormData(elements) {
return Object.keys(elements).reduce(function (acc, key) {
var elem = elements[key]
acc[key] = valueOfElement(elem)
return acc
}, {})
}
function valueOfElement(elem) {
if (typeof elem === "function") {
return elem()
} else if (containsRadio(elem)) {
var elems = toList(elem)
var checked = elems.filter(function (elem) {
return elem.checked
})[0] || null
return checked ? checked.value : null
} else if (Array.isArray(elem)) {
return elem.map(valueOfElement).filter(filterNull)
} else if (elem.tagName === undefined && elem.nodeType === undefined) {
return FormData(elem)
} else if (elem.tagName === "INPUT" && isChecked(elem)) {
if (elem.hasAttribute("value")) {
return elem.checked ? elem.value : null
} else {
return elem.checked
}
} else if (elem.tagName === "INPUT") {
return elem.value
} else if (elem.tagName === "TEXTAREA") {
return elem.value
} else if (elem.tagName === "SELECT") {
return elem.value
}
}
function isChecked(elem) {
return elem.type === "checkbox" || elem.type === "radio"
}
function containsRadio(value) {
if (value.tagName || value.nodeType) {
return false
}
var elems = toList(value)
return elems.some(function (elem) {
return elem.tagName === "INPUT" && elem.type === "radio"
})
}
function toList(value) {
if (Array.isArray(value)) {
return value
}
return Object.keys(value).map(prop, value)
}
function prop(x) {
return this[x]
}
function filterNull(val) {
return val !== null
}