回答編集履歴
1
コード追記、data-\* 属性に言及
test
CHANGED
@@ -1,16 +1,88 @@
|
|
1
|
+
### label 要素
|
2
|
+
|
3
|
+
|
4
|
+
|
1
5
|
label要素を使う方法が良いと思います。
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
- [ラベル文を参照する - JSFiddle](https://jsfiddle.net/2ppu4vze/)
|
2
10
|
|
3
11
|
|
4
12
|
|
5
13
|
```HTML
|
6
14
|
|
15
|
+
<form id="phone">
|
16
|
+
|
7
|
-
<label><input type="checkbox" name="mobile" value = "500">
|
17
|
+
<label><input type="checkbox" name="mobile" value = "500">Android</label>
|
18
|
+
|
19
|
+
<label><input type="checkbox" name="mobile" value = "800">iPhone</label>
|
20
|
+
|
21
|
+
<input type="submit" value="total">
|
22
|
+
|
23
|
+
</form>
|
24
|
+
|
25
|
+
<pre id="output"></pre>
|
26
|
+
|
27
|
+
|
8
28
|
|
9
29
|
<script>
|
10
30
|
|
11
31
|
'use strict';
|
12
32
|
|
33
|
+
(function () {
|
34
|
+
|
35
|
+
function handleSubmit (event) {
|
36
|
+
|
37
|
+
var inputs = event.target.elements['mobile'],
|
38
|
+
|
39
|
+
price = 0,
|
40
|
+
|
41
|
+
names = [];
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
for (var i = 0, l = inputs.length, input; i < l; ++i) {
|
46
|
+
|
47
|
+
input = inputs[i];
|
48
|
+
|
49
|
+
if (input.checked) {
|
50
|
+
|
51
|
+
price += Number(input.value);
|
52
|
+
|
53
|
+
names.push(input.labels[0].textContent);
|
54
|
+
|
55
|
+
}
|
56
|
+
|
57
|
+
}
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
event.preventDefault();
|
62
|
+
|
13
|
-
|
63
|
+
input.ownerDocument.getElementById('output').textContent = [
|
64
|
+
|
65
|
+
'選択された商品は' + (names.length ? names : 'ない') + 'ですね。',
|
66
|
+
|
67
|
+
'合計は' + price + '円になります。'
|
68
|
+
|
69
|
+
].join('\n');
|
70
|
+
|
71
|
+
}
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
function main () {
|
76
|
+
|
77
|
+
this.document.getElementById('phone').addEventListener('submit', handleSubmit, false);
|
78
|
+
|
79
|
+
}
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
main.call(this);
|
84
|
+
|
85
|
+
}.call(this));
|
14
86
|
|
15
87
|
</script>
|
16
88
|
|
@@ -18,4 +90,24 @@
|
|
18
90
|
|
19
91
|
|
20
92
|
|
93
|
+
### 代替案
|
94
|
+
|
95
|
+
|
96
|
+
|
97
|
+
「checkbox に 2つのvalue を持たせる」という要件だけ考えると次の方法も考えられます。
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
- data-* 属性
|
102
|
+
|
103
|
+
- value属性値にCSV形式で格納する (ex: `500,Android`)
|
104
|
+
|
105
|
+
- value属性値にJSON形式(配列)で格納する (ex: `[500,"Android"]`)
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
実質的にはラベル文と同じ文字列を格納する事になるので、label要素をお勧めしています。
|
110
|
+
|
111
|
+
|
112
|
+
|
21
113
|
Re: margutta さん
|