# JavaScript: Calculate the volume of a sphere

## JavaScript DOM: Exercise-10 with Solution

Write a JavaScript program to calculate sphere volume.

Sample Output of the form :

Sample Solution:

HTML Code:

``````<!-- Declaration of HTML document type -->
<!doctype html>
<!-- Start of HTML document -->
<html lang="en">
<!-- Declaring character encoding -->
<meta charset="utf-8">
<!-- Setting title of the document -->
<title>Volume of a Sphere</title>
<!-- Internal CSS styling -->
<style>
/* Styling body to have padding at the top */
/* Styling label and input elements to display as block */
label,input{display:block;}
</style>
<!-- Start of body section -->
<body>
<!-- Paragraph explaining the purpose of the form -->
<p>Input radius value and get the volume of a sphere.</p>
<!-- Form for inputting radius and displaying volume -->
<form action="" method="post" id="MyForm">
<!-- Label and input field for entering radius -->
<!-- Label and input field for displaying volume -->
<label for="volume">Volume</label><input type="text" name="volume" id="volume">
<!-- Submit button for calculating volume -->
<input type="submit" value="Calculate" id="submit">
</form>
<!-- End of body section -->
</body>
<!-- End of HTML document -->
</html>
```
```

JavaScript Code:

``````// Function declaration for volume_sphere
function volume_sphere()
{
// Variable to hold the volume
var volume;
// Getting the radius value from the input field
// Taking absolute value of radius to ensure it's positive
// Calculating the volume of the sphere
volume = (4/3) * Math.PI * Math.pow(radius, 3);
// Rounding the volume to 4 decimal places
volume = volume.toFixed(4);
// Setting the calculated volume in the volume input field
document.getElementById('volume').value = volume;
// Returning false to prevent form submission
return false;
}
// Attaching volume_sphere function to window.onload and form submit event
```
```

Output:

Flowchart:

Live Demo:

See the Pen javascript-dom-exercise-10 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿