Home > Web Front-end > JS Tutorial > body text

How to implement a simple calculator in js

王林
Release: 2020-03-12 11:17:53
forward
2421 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
js
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template