Hello, everyone! I'm new to JavaScript and still learning the ropes, so please bear with me. I have a task at hand where I need to calculate the volume of a cylinder using constructor functions and prototypes.
The challenge lies in extracting values from input fields in a form, performing the calculation, and displaying the result in another input field upon clicking a button to create a new instance.
However, I've hit a roadblock as my console keeps throwing errors indicating that 'height' and 'diameter' are undefined when the button is clicked.
I've spent almost an entire day on this issue without making much progress...
Below is the code snippet I've been working on:
<form action="">
<label>
Diameter: <input type="text" id="diameter"><br><br>
Height: <input type="text" id="height"> <br><br>
<input type="button" value="calculate" id="calculateBtn"><br><br>
<input type="text" id="output">
</label>
</form>
<script>
window.addEventListener("DOMContentLoaded", function () {
document.getElementById("calculateBtn").addEventListener("click", calculate);
});
function Cylinder(height, diameter) {
this.height = height;
this.diameter = diameter;
}
Cylinder.prototype.volume = function () {
var radius = document.getElementById('diameter').value / 2;
var height = document.getElementById('height').value;
var calculation = Math.PI * radius * radius * height;
//calculation.toFixed(4);
}
function calculate() {
var myCylinder = new Cylinder(
document.getElementById("output").value = Cylinder()
)
console.log(myCylinder);
}
</script>