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:
<form action=""> <label> Diameter: <input type="text" id="diameter"><br><br> Hoogte: <input type="text" id="hoogte"> <br><br> <input type="button" value="bereken" id="berekenBtn"><br><br> <input type="text" id="uitkomst"> </label> </form>
<script> window.addEventListener("DOMContentLoaded", function () { document.getElementById("berekenBtn").addEventListener("click", bereken); }); function Cylinder(hoogte, diameter) { this.hoogte = hoogte; this.diameter = diameter; } Cylinder.prototype.volume = function () { var radius = document.getElementById('diameter') = this.diameter / 2; var hoogte = document.getElementById('hoogte') = this.hoogte; var berekening = Math.PI * radius * radius * hoogte; //berekening.toFixed(4); } function bereken() { var myCylinder = new Cylinder( document.getElementById("uitkomst").value = Cylinder() ) console.log(myCylinder); } </script>
Advertisement
Answer
<form action=""> <label> Diameter: <input type="number" id="diameter"><br><br> Hoogte: <input type="number" id="hoogte"> <br><br> <input type="button" value="bereken" id="berekenBtn"><br><br> <input type="text" id="uitkomst"> </label> </form> <script> window.addEventListener("DOMContentLoaded", function () { document.getElementById("berekenBtn").addEventListener("click", bereken); }); function Cylinder(hoogte, diameter) { this.hoogte = hoogte; this.diameter = diameter; } Cylinder.prototype.volume = function () { var radius = this.diameter / 2; var hoogte = this.hoogte; var berekening = Math.PI * radius * radius * hoogte; return berekening; } function bereken() { var diameter = document.getElementById("diameter").value; var hoogte = document.getElementById("hoogte").value; var myCylinder = new Cylinder(diameter, hoogte); var result = myCylinder.volume(); document.getElementById("uitkomst").value = result; } </script>
I have modified some code, try to understand this, hope it will helps you !