I’m a JavaScript noob and beginner so don’t get too hard on me.
I need to calculate the volume of a cylinder using a constructor function and prototype.
I’ve got a form with two inputs which I’ll be getting the values from to do the calculation with. I have to create a new instance when the button is clicked and the calculation has to be outputted in the outcome input.
I seem to be stuck at the part to get the values out of the inputs as my console always says that ‘hoogte’ and ‘diameter’ is undefined when I click the button.
I’ve been looking at this for almost 24h now, but I’m not getting any progress..
This is my code:
JavaScript
x
9
1
<form action="">
2
<label>
3
Diameter: <input type="text" id="diameter"><br><br>
4
Hoogte: <input type="text" id="hoogte"> <br><br>
5
<input type="button" value="bereken" id="berekenBtn"><br><br>
6
<input type="text" id="uitkomst">
7
</label>
8
</form>
9
JavaScript
1
27
27
1
<script>
2
window.addEventListener("DOMContentLoaded", function () {
3
document.getElementById("berekenBtn").addEventListener("click", bereken);
4
});
5
6
function Cylinder(hoogte, diameter) {
7
this.hoogte = hoogte;
8
this.diameter = diameter;
9
}
10
11
Cylinder.prototype.volume = function () {
12
var radius = document.getElementById('diameter') = this.diameter / 2;
13
var hoogte = document.getElementById('hoogte') = this.hoogte;
14
15
var berekening = Math.PI * radius * radius * hoogte;
16
//berekening.toFixed(4);
17
}
18
19
20
function bereken() {
21
var myCylinder = new Cylinder(
22
document.getElementById("uitkomst").value = Cylinder()
23
)
24
console.log(myCylinder);
25
}
26
</script>
27
Advertisement
Answer
JavaScript
1
39
39
1
<form action="">
2
<label>
3
Diameter: <input type="number" id="diameter"><br><br>
4
Hoogte: <input type="number" id="hoogte"> <br><br>
5
<input type="button" value="bereken" id="berekenBtn"><br><br>
6
<input type="text" id="uitkomst">
7
</label>
8
</form>
9
10
11
<script>
12
window.addEventListener("DOMContentLoaded", function () {
13
document.getElementById("berekenBtn").addEventListener("click", bereken);
14
});
15
16
function Cylinder(hoogte, diameter) {
17
this.hoogte = hoogte;
18
this.diameter = diameter;
19
}
20
21
Cylinder.prototype.volume = function () {
22
var radius = this.diameter / 2;
23
var hoogte = this.hoogte;
24
25
var berekening = Math.PI * radius * radius * hoogte;
26
return berekening;
27
}
28
29
30
function bereken() {
31
var diameter = document.getElementById("diameter").value;
32
var hoogte = document.getElementById("hoogte").value;
33
var myCylinder = new Cylinder(diameter, hoogte);
34
var result = myCylinder.volume();
35
document.getElementById("uitkomst").value = result;
36
}
37
38
</script>
39
I have modified some code, try to understand this, hope it will helps you !