-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
95 lines (84 loc) · 1.92 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
/**
* Module dependencies.
*/
var typeOf = require('type');
/**
* 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;
}