Search code examples
javascriptcalculatorvolume

Sphere Volume Calculator


Hello I am making a volume calculator and I can't seem to get the volume to display on screen. Would doing an alert solve this? This assignment requires me to use anonymous functions so I am having a hard time getting the function to run.

HTML
 <body>
 <h3> Calculate the Volume of a Sphere <h3>
 <label for="radius">Radius </label>
 <input id="radius" name="radius"  required>
 </input>

 <button id="calc" onclick=sphereVol> calculate </button>

JavaScript

 var sphereVol = function(radius){
 var c = (4/3) * Math.PI * Math.pow(radius, 3);
 return c;
 }

Solution

  • You need to get the radius from the input and the output it somewhere. You could use alert() or console.log() but it's nicer if you can output to the page. document.getElementById() is a fundamental way of getting elements from the DOM and value can help get the input. Here's a super-simplified version:

    var sphereVol = function() {
      // get the radius
      let radius = document.getElementById('radius').value
      var c = (4 / 3) * Math.PI * Math.pow(radius, 3);
      // display the result
      document.getElementById('result').textContent = "Volume ≈ " + c.toFixed(4);
    }
    <h3> Calculate the Volume of a Sphere
    </h3>
    <label for="radius">Radius </label>
    <input id="radius" name="radius" required>
    </input>
    
    <button id="calc" onclick="sphereVol()"> calculate </button>
    <div id="result">
    </div>