I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn’t show anything. So what is wrong with my JS? Do I need to include a jQuery file?
JavaScript
x
44
44
1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2
<html>
3
<head>
4
</head>
5
<body>
6
<form id="frm1" action="Calculate.html">
7
<table width="350px" border="1px">
8
<tr>
9
<th colspan="2">Availability</th>
10
</tr>
11
<tr>
12
<td>Total Production Time</td>
13
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
14
</tr>
15
<tr>
16
<td>Breaks</td>
17
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
18
</tr>
19
<tr>
20
<td>Malfunctions</td>
21
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
22
</tr>
23
<tr>
24
<td>Theoretical production time:</td>
25
<td><p id="test"></p></td>
26
</tr>
27
</table>
28
29
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
30
<script>
31
function Calculate()
32
{
33
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
34
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
35
var Breaks = document.getElementById("Breaks").value;
36
var Malfunctions = document.getElementById("Malfunctions").value;
37
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
38
39
document.getElementById("test").innerHTML = TheoreticalProductionTime;
40
}
41
</script>
42
43
</body>
44
</html>
Advertisement
Answer
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don’t give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
JavaScript
1
9
1
function Calculate() {
2
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
3
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
4
var Breaks = document.getElementById("Breaks").value;
5
var Malfunctions = document.getElementById("Malfunctions").value;
6
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
7
8
document.getElementById("test").innerHTML = TheoreticalProductionTime;
9
}
JavaScript
1
29
29
1
<form id="frm1" action="Calculate.html">
2
<table width="350px" border="1px">
3
<tr>
4
<th colspan="2">Availability</th>
5
</tr>
6
<tr>
7
<td>Total Production Time</td>
8
<td>
9
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
10
</tr>
11
<tr>
12
<td>Breaks</td>
13
<td>
14
<input type="number" id="Breaks" placeholder="">minutes</td>
15
</tr>
16
<tr>
17
<td>Malfunctions</td>
18
<td>
19
<input type="number" id="Malfunctions" placeholder="">minutes</td>
20
</tr>
21
<tr>
22
<td>Theoretical production time:</td>
23
<td>
24
<p id="test"></p>
25
</td>
26
</tr>
27
</table>
28
<input type="button" onclick="Calculate()" value="calculate">
29
</form>