Practical – 116.2 : Create a Simple Calculator in JS
Program Code :
<!DOCTYPE html>
<html>
<head>
 <title>Simple Calculator</title>
 <style>
   body {
     text-align: center;
     margin-top: 50px;
     font-family: Arial;
   }
   .calculator {
     display: inline-block;
     padding: 20px;
     border-radius: 10px;
     box-shadow: 0 0 10px #888;
     background-color: #f2f2f2;
   }
   input[type=”button”] {
     width: 60px;
     height: 40px;
     margin: 5px;
     font-size: 18px;
   }
   #result {
     width: 250px;
     height: 40px;
     margin-bottom: 10px;
     font-size: 20px;
     text-align: right;
     padding-right: 10px;
   }
 </style>
</head>
<body>
 <h2>Simple Calculator</h2>
 <div class=”calculator”>
   <input type=”text” id=”result” disabled><br>
   <input type=”button” value=”7″ onclick=”append(‘7’)”>
   <input type=”button” value=”8″ onclick=”append(‘8’)”>
   <input type=”button” value=”9″ onclick=”append(‘9’)”>
   <input type=”button” value=”/” onclick=”append(‘/’)”><br>
   <input type=”button” value=”4″ onclick=”append(‘4’)”>
   <input type=”button” value=”5″ onclick=”append(‘5’)”>
   <input type=”button” value=”6″ onclick=”append(‘6’)”>
   <input type=”button” value=”*” onclick=”append(‘*’)”><br>
   <input type=”button” value=”1″ onclick=”append(‘1’)”>
   <input type=”button” value=”2″ onclick=”append(‘2’)”>
   <input type=”button” value=”3″ onclick=”append(‘3’)”>
   <input type=”button” value=”-” onclick=”append(‘-‘)”><br>
   <input type=”button” value=”0″ onclick=”append(‘0’)”>
   <input type=”button” value=”C” onclick=”clearResult()”>
   <input type=”button” value=”=” onclick=”calculate()”>
   <input type=”button” value=”+” onclick=”append(‘+’)”><br>
 </div>
 <script>
   function append(value) {
     document.getElementById(“result”).value += value;
   }
   function clearResult() {
     document.getElementById(“result”).value = “”;
   }
   function calculate() {
     try {
       document.getElementById(“result”).value = eval(document.getElementById(“result”).value);
     } catch (e) {
       alert(“Invalid Expression”);
       clearResult();
     }
   }
 </script>
</body>
</html>