forked from component/value
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
110 lines (97 loc) · 2.41 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
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
/**
* Set or get `el`'s' value.
*
* @param {Element} el
* @param {Mixed} val
* @return {Mixed}
* @api public
*/
module.exports = function(el, val){
if (2 == arguments.length) return set(el, val);
return get(el);
};
/**
* Get `el`'s value.
*/
function get(el) {
switch (type(el)) {
case 'checkbox':
case 'radio':
if (el.checked) {
var attr = el.getAttribute('value');
return null == attr ? true : attr;
} else {
return false;
}
case 'radiogroup':
for (var i = 0, radio; radio = el[i]; i++) {
if (radio.checked) return radio.value;
}
break;
case 'select':
for (var i = 0, option; option = el.options[i]; i++) {
if (option.selected) return option.value;
}
break;
default:
return el.value;
}
}
/**
* Set `el`'s value.
*/
function set(el, val) {
switch (type(el)) {
case 'checkbox':
case 'radio':
if (val) {
el.checked = true;
} else {
el.checked = false;
}
break;
case 'radiogroup':
for (var i = 0, radio; radio = el[i]; i++) {
radio.checked = radio.value === val;
}
break;
case 'select':
for (var i = 0, option; option = el.options[i]; i++) {
option.selected = option.value === val;
}
break;
default:
el.value = val;
}
}
/**
* Element type.
*/
function type(el) {
var group = 'array' == typeOf(el) || 'object' == typeOf(el);
if (group) el = el[0];
var name = el.nodeName.toLowerCase();
var type = el.getAttribute('type');
if (group && type && 'radio' == type.toLowerCase()) return 'radiogroup';
if ('input' == name && type && 'checkbox' == type.toLowerCase()) return 'checkbox';
if ('input' == name && type && 'radio' == type.toLowerCase()) return 'radio';
if ('select' == name) return 'select';
return name;
}
function typeOf(val) {
switch (Object.prototype.toString.call(val)) {
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object Error]': return 'error';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val !== val) return 'nan';
if (val && val.nodeType === 1) return 'element';
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val)
return typeof val;
}