We have learned how to create a calculator that calculates the volume of a cuboid. Using the similar script, we can write a JavaScript that allows the user to input the dimensions as well as enter the answer. If the answer is wrong, it will displays the “Incorrect” message, otherwise it will show the “Correct” message.
The JavaScript is as follows:’
function Calvol(width, length, height){
var vol=width*length*height;
return vol;
}
function CalSize(){
var x=parseInt(document.getElementById(“wdt”).value);
var y=parseInt(document.getElementById(“lgt”).value);
var z=parseInt(document.getElementById(“hgt”).value);
var Size=Calvol(x,y,z);
var answer=document.getElementById(‘ans1’).value;
if (answer==Size)
{message=”Correct”;}
else
{message=”Incorrect, try again”;}
document.getElementById(‘ans’).textContent=message;
}
And the html is as follows:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″>
<title>Volume Calculation</title>
</head>
<body onload=”RandomFn()”>
<h1>Volume of a Cuboid</h1>
<p>Width = <input type=”text” size=”5″ id=”wdt”></p>
<p>Length= <input type=”text” size=”5″ id=”lgt”></p>
<p>Height= <input type=”text” size=”5″ id=”hgt”></p>
<h3>The Volume is</h3>
<input type=”text” size=”5″ id=”ans1″><br><br>
<h3 id=”ans”><h3>
<script>
function Nextq() {
location.reload();
}
</script>
<input type=”button” value=”Check Answer” onclick=”CalSize()”><br><br>
<input type=”button” value=”Next Question” onclick=” location.reload();”>
<script>
function RandomFn() {
document.getElementById(“wdt”).innerHTML = parseInt(Math.random()*9+1);
document.getElementById(“lgt”).innerHTML = parseInt(Math.random()*9+1);
document.getElementById(“hgt”).innerHTML = parseInt(Math.random()*9+1);
}
</script>
<script type=”text/javascript” src=”volume2.js”></script>
</body>
</html>
Click Here to run the script.