Determine the cylinder's volume using JavaScript and the prototype method

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>

Answer №1

 <form action="">
        <label>
            Base: <input type="number" id="base"><br><br>
            Height: <input type="number" id="height"> <br><br>
            <input type="button" value="calculate" id="calculateBtn"><br><br>
            <input type="text" id="result">
        </label>
    </form>


<script>
         window.addEventListener("DOMContentLoaded", function () {
        document.getElementById("calculateBtn").addEventListener("click", calculate);
    });

    function Triangle(height, base) {
        this.height = height;
        this.base = base;
    }

    Triangle.prototype.area = function () {
        var b =  this.base;
        var h = this.height;

        var calculation = 0.5 * b * h;
        return calculation;
    }


    function calculate() {
        var base = document.getElementById("base").value;
        var height = document.getElementById("height").value;
        var myTriangle = new Triangle(base, height);
        var result = myTriangle.area();
        document.getElementById("result").value = result;
    }

    </script>

I have made some changes to the code for calculating triangle area, hopefully this helps you understand it better!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to fully eliminate the Pixi renderer, stage, and all associated assets

I am currently faced with a challenge of mounting and unmounting a Pixi stage using React without relying on react-pixi. Upon re-mounting the component, I encounter the following error: Uncaught Error: Resource with name "cupCake.png" already exists i.ad ...

Designate material for a particular table header element

Is there a method to pass content within a td-element to a specific th-element? I am working with a dynamic table and need to associate the content correctly under each table header. I have implemented pagination for the rows in the table. Currently, all ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...

Exploring JSON Object Iteration Using jQuery for AJAX Requests in JavaScript

I am struggling to grasp this concept. Currently, I have a JSON file that contains a collection of hospitals, including their addresses, operating hours, and phone numbers. My goal is to make an AJAX call to retrieve data from the JSON file and display i ...

code shatters console.log()!

I'm confused about the output I'm seeing: let frenchWords; const fs = require('fs'); const data = fs.readFileSync('frenchVerbsList.txt', 'utf8'); frenchWords = data.split('\n'); console.log(Array.isA ...

Guidelines for submitting on button click within MaterialUI stepper

I am currently developing a Register Form utilizing MaterialUI stepper. Each step in the form corresponds to a specific component: const steps = ['Basic information', 'Profile', 'Review registration'] At the final step of the ...

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

Issues with Bootstrap tabs not updating content

I have been working on incorporating bootstrap tabs into one of our pages. I followed the example provided at https://getbootstrap.com/docs/4.0/components/navs/#javascript-behavior, but unfortunately, the tabs are not functioning correctly (they appear as ...

If condition cannot be executed

It seems like there should be a simple solution to this issue, but I am struggling to understand why the errors persist in my if statement. The syntax errors are becoming a problem with this if statement: if (selectedDate < new Date().toISOS ...

Universal customization for Material-UI Select

I am attempting to customize the appearance of a select component within a React project using MUI 5. Specifically, I want to modify the border size and color when the select component is in focus. While other components can be styled globally using styleO ...

What steps can I take to ensure my website is mobile-friendly?

My website isn't displaying correctly on cellphones. According to the tutorial I'm following, it should look like this: https://i.sstatic.net/XNDfQ.png However, this is how it appears on my Samsung Galaxy S5: https://i.sstatic.net/veHTP.png I ...

Javascript function always runs last despite being called first

I am facing a situation where I have two functions associated with the Vue object named "form": form.sizeChartAsImage(); form.setSizeChart(); The code for these functions is as follows: setSizeChart: function () { for (i = 0; i < this.col ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

Ordering styles in Material UI

I've spent countless hours customizing this element to perfection, but the more I work on it, the more of a headache it gives me. The element in question is an outlined TextField, and my focus has been on styling its label and border. Initially, I th ...

What is the best way to retrieve an attribute from a class within the __init__ method of a different class?

Currently tackling an OOP assignment where we're diving into creating classes for the first time. Our task involves developing two classes: Animal and Desert. There are specific attributes and methods outlined for us that must be included in these cl ...

PHP: Safely Submitting Scores Using JavaScript

I have developed a PHP file that updates scores in a database. For example: http://domain.com/heli/test.php?id=100001181378824&score=50000 The code in test.php is as follows: mysql_connect(localhost,$user,$password); $id = mysql_real_escape_string($_ ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...