In onderstaande code zie je dat het basisproduct (fruitmand) 19 euro kost. Optioneel kunnen klanten daar modules (fruit, wijn, etc) bij aanschaffen. Elke module heeft een prijs. De totaalprijs moet automatisch berekend worden als een klant een module aan- of uitklikt:
In de variabele "options" wordt de totaalprijs uitgerekend. Standaard is deze dus 19 euro. In regel 31 wordt de waarde van de aangevinkte checkboxes hierbij opgeteld. Alleen: "options" wordt als een string behandeld en wordt bijvoorbeeld 19150 in plaats van (19 + 150 =) 169. Hoe los ik dit op?
code:
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
| <form onload="calculate()">
<table border="1">
<tr>
<td> </td><td>Beginprijs</td><td>19</td>
</tr>
<tr>
<td><input name="module" value="100" type="checkbox" onchange="calculate()"></td>
<td>Module A</td>
<td>100</td>
</tr>
<tr>
<td><input name="module" value="150" type="checkbox" onchange="calculate()"></td>
<td>Module B</td>
<td>150</td>
</tr>
<tr>
<td> </td>
<td>Prijs</td>
<td><input name="price" type="text" size="10"></td>
</tr>
</table>
</form>
<script>
function calculate() {
var modules = document.forms[0].module;
var options = 19;
for (var i = 0; i < modules.length; i++) {
if (modules[i].checked) {
options += modules[i].value;
}
}
document.forms[0].price.value = options;
}
</script> |
In de variabele "options" wordt de totaalprijs uitgerekend. Standaard is deze dus 19 euro. In regel 31 wordt de waarde van de aangevinkte checkboxes hierbij opgeteld. Alleen: "options" wordt als een string behandeld en wordt bijvoorbeeld 19150 in plaats van (19 + 150 =) 169. Hoe los ik dit op?
"Real software engineers work from 9 to 5, because that is the way the job is described in the formal spec. Working late would feel like using an undocumented external procedure."