Programming Examples
JavaScript code to design a simple calculator to perform the following operations sum product difference and quotient
Write a JavaScript to design a simple calculator to perform the following operations: sum, product, difference and quotient.
Solution
<!DOCTYPE html>
<html>
<head>
<title>Basic Calculator</title>
<script language="javascript">
function cal()
{
var n1,n2,res,opr;
n1=parseInt(document.getElementById("t1").value);
n2=parseInt(document.getElementById("t2").value);
opr=document.getElementById("s1").value;
switch(opr)
{
case '+':
res=n1+n2;
document.getElementById("t3").value=res;
break;
case '-':
res=n1-n2;
document.getElementById("t3").value=res;
break;
case '*':
res=n1*n2;
document.getElementById("t3").value=res;
break;
case '/':
res=n1/n2;
document.getElementById("t3").value=res;
break;
default:
document.getElementById("t3").value="Invalid Operator";
}
}
</script>
</head>
<body>
<form>
<table>
<tr>
<td>Number 1</td>
<td><input type="number" id="t1"/></td>
</tr>
<tr>
<td>Number 2</td>
<td><input type="number" id="t2"/></td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="t3"/></td>
</tr>
<tr>
<td>Select Operation</td>
<td>
<select id="s1">
<option value="">Select Operation</option>
<option value="+">Addition</option>
<option value="-">Substraction</option>
<option value="*">Product</option>
<option value="/">Quotient</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Calculate" onClick="cal()"/></td>
</tr>
</table>
</form>
</body>
</html>
Output