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

JavaScript implements a simple calculator

高洛峰
Release: 2017-02-04 13:53:50
Original
1089 people have browsed it

Preface

hello, everyone, I have been studying for a while, and I have learned about the framework and background content. In order to prevent the front-end js and jq from not being proficient enough and forgetting many algorithms and basic usage, I will continue. Continue to update some small functional effect codes for recording and accumulation. There are many shortcomings. Encapsulation and code redundancy are not strictly required for the time being. Try our best to improve and keep updated..

Simple addition, subtraction, multiplication and division calculator , using the value value of the form, implemented with native js. It can be copied directly to the editor, opened and run.

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>加减乘除计算器</title> 
 <script type="text/javascript">
  function count(){  
  var a = parseInt(document.getElementById("txt1").value);
  var b = parseInt(document.getElementById("txt2").value) ;
  var sign = document.getElementById("select").value;
  var result = 0;
    switch(sign){
      case "+": result = a+b;
      break;
      case "-": result = a-b;
      break;
      case "*": result = a*b;
      break;
      case "/": result = a/b;
      break;
      case "%": result = a%b;
      break;
     }
  document.getElementById("answer").value = result;
  }
 </script> 
 </head> 
 <body>
  <input type=&#39;text&#39; id=&#39;txt1&#39; /> 
  <select id=&#39;select&#39;>
    <option value=&#39;+&#39;>+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
    <option value="%">%</option>
  </select>
  <input type=&#39;text&#39; id=&#39;txt2&#39; /> 
    <input type=&#39;button&#39; value=&#39; = &#39; onclick="count()"/> 
    <!--通过 = 按钮来调用创建的函数,得到结果-->
  <input type=&#39;text&#39; id=&#39;answer&#39; />  
 </body>
</html>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I hope everyone will support the PHP Chinese website.

For more articles related to JavaScript implementation of simple calculator, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!