Creating a Simple Calculator

We can create a simple calculator that adds two numbers.

First we create a function that generates two random numbers that are less than 100 and converts them into integers , as follows:

<script>
function RandomFn() {
document.getElementById(“num1”).innerHTML = parseInt(Math.random()*100);
document.getElementById(“num2”).innerHTML = parseInt(Math.random()*100);

}

The innerHTML property is to specify the HTML content of an element. The parseInt function is to convert a number into interger so that it can be manipulated mathematically.

The function to add two numbers is shown as follows:

function myFunction() {
var number1;
var number2;
number1=document.getElementById(‘num1’).innerHTML ;
number2=document.getElementById(‘num2’).innerHTML;
var sum=parseInt(number1)+parseInt(number2);
document.getElementById(‘ans’).textContent=”The sum of two numbers= “+sum;
}

textContent method is to display the output within a HTML element.

The complete HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<title>Simple JS Calculator></title>
<meta name=viewport content=”width=device-width, initial-scale=1″>
</head>
<body onload=”RandomFn()”>
<script type=”text/javascript” src=”kidmath.js”></script>
<h3>Addition of Two Numbers</h3>
<p>Please calculate the sum of two numbers.</p>
<form id=”Myform”>
Number 1: <b id=”num1″></b><br><br>
Number 2: <b id=”num2″></b>
<p id=”ans”>Calculate the sum of two numbers</p><br>
<input type=”button” value=”Calculate” onclick=”myFunction()”><br><br>
<input type=”button” value=”Next Question” onclick=”Nextq()”>
</form>
<script>
function Nextq() {
location.reload();
}
</script>
<script>
function RandomFn() {
document.getElementById(“num1”).innerHTML = parseInt(Math.random()*100);
document.getElementById(“num2”).innerHTML = parseInt(Math.random()*100);

}
</script>

</body>
</html>

Click Simple Calculator to see the output.