DEV Community

Alan K
Alan K

Posted on

Simple JavaScript + HTML Calculator

Hi ,this calculator project is a basic and simple project. In this project we are focusing more on javascript and html. In this project we will use the "eval()" function, which make it easy to do the problems. So let's jump to the tutorial.

BUY ME A COFFEE - https://bit.ly/3FN8thW

REQUIREMENTS:

  • Any, text editor(which is capable of saving a file with .html extenstion).

STEPS:

  • Open the text editor.

  • Follow the below codes

<html>
<head>

   <title>My Calculator</title>

   <!--i haven't focused on css , you can improve it-->
   <style>
      input .ans
      {
      height:"90";
      width:"400";
      }
   </style>
</head>

   <body>
       <!--buttons-->
      <h1 style="font-family:Verdana">My Calculator</h1>
      <input type='text'  id="ans">
      <br>
      <br>
      <input type='button' value='1'style="width:75px;" onclick='dis(1)'> 
      <input type='button' value='2'style="width:75px;"onclick='dis(2)'>
      <input type='button' value='3'style="width:75px;"onclick='dis(3)'>
      <input type='button' value='/'style="width:75px;"onclick='dis("/")'>
      <br>
      <br>
      <input type='button' value='4'style="width:75px;"onclick='dis(4)'>
      <input type='button' value='5'style="width:75px;"onclick='dis(5)'>
      <input type='button' value='6'style="width:75px;"onclick='dis(6)'>
      <input type='button' value='*'style="width:75px;"onclick='dis("*")'>
      <br>
      <br>
      <input type='button' value='7'style="width:75px;"onclick='dis(7)'>
      <input type='button' value='8'style="width:75px;"onclick='dis(8)'>
      <input type='button' value='9'style="width:75px;"onclick='dis(9)'>
      <input type='button' value='-'style="width:75px;"onclick='dis("-")'>
      <br>
      <br>
      <input type='button' value='0'style="width:75px;"onclick='dis(0)'>
      <input type='button' value='+'style="width:75px;"onclick='dis("+")'>
      <input type='button' value='='style="width:155px;"onclick='solve()'>
      <br>
      <br>
      <input type='button' value='CLEAR'style="width:310px;"onclick='clr()'>

        <!--Javascript-->
    <script>
      function dis(val)
      {
      document.getElementById("ans").value+=val
      }
      function solve()
      {
      let x =  document.getElementById("ans").value
      let y = eval(x)
      document.getElementById("ans").value =y
      }
      function clr()
      {
      document.getElementById("ans").value =""
      }
   </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)