Home  >  Article  >  Web Front-end  >  How to implement a simple calculator in js

How to implement a simple calculator in js

王林
王林forward
2020-03-12 11:17:532420browse

How to implement a simple calculator in js

Rendering:

How to implement a simple calculator in js

#First, we create the elements needed for the page in the body

<body>
 <input type="text" id="ipt1">
 <select name="" id="slt">
  <option value="+">+</option>
  <option value="-">-</option>
  <option value="*">*</option>
  <option value="/">/</option>
 </select>
 <input type="text" id="ipt2">
 <button id="btn">=</button>
 <input type="text" id="ipt3">
</body>

Above You can choose the ID at will, as long as it is easy to use.

(Recommended tutorial: javascript tutorial)

javascript code:

<body>
 <script>
  //获取页面标签的元素
  var inpt1 = document.getElementById("ipt1");
  var inpt2 = document.getElementById("ipt2");
  var inpt3 = document.getElementById("ipt3");
  var selt = document.getElementById("slt");
  var butn = document.getElementById("btn");
   
 //给等于按钮添加点击事件
  butn.onclick = function(){
   //将三个输入框的value值分别赋给变量t1,t2,t3中
   var t1 = parseFloat(ipt1.value);
   var t2 = parseFloat(ipt2.value);
   var t3 = parseFloat(ipt3.value);
 
 //定义一个结果变量用于存放结果
   var endValue;
   //用switch语句来写运算语句
   switch(slt.value){
    case "+":
    endValue = t1 + t2;
    break;
    case "-":
    endValue = t1 - t2;
    break;
    case "*":
    endValue = t1 * t2;
    break;
    case "/":
    endValue = t1 / t2;
    break;
    default:
    endValue = t1 + t2;
    break;
   }
   //将结果放入结果输入框的value值中,在页面上显示
   inpt3.value = endValue;
  }
 </script>
</body>

Recommended related video tutorial: javascript video tutorial

The above is the detailed content of How to implement a simple calculator in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete