search
HomeWeb Front-endJS TutorialPure javascript code to implement calculator function (three methods)

Today I will share a calculator program written in pure JavaScript code. This program can be used in many industries, such as making decoration budgets, loan interest rates, etc.

First let’s take a look at the finished effect:

Pure javascript code to implement calculator function (three methods)

Method 1:

The specific code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>计算器</title>
<style type="text/css">
*{margin:0px;padding:0px}
table{width:300px;margin:100px auto}
td{height:30px;text-align:center;line-height:30px;border:1px solid #ccc;font-size:14px} input{float:left;margin-left:30px;display:inline}
#jia,#jian,#cheng,#chu{width:30px}
</style>
<script type="text/javascript">
//以下所有的注释通用语所有的加减乘除算法。
//加法运算
function jia(){
//定义变量a,b,c
var x,y,z;
}; //通过document分别获取x,y的值 x=document.getElementById("num1").value; y=document.getElementById("num2").value; //修改x,y的字符类型,并且得到z的值 z=parseInt(x)+parseInt(y); //将z的值赋给id=result document.getElementById("result").value=z;
//减法运算
function jian(){
var x,y,z;
x=document.getElementById("num1").value;
y=document.getElementById("num2").value;
z=parseInt(x)-parseInt(y);
document.getElementById("result").value=z;
};
//乘法运算
function cheng(){
var x,y,z;
x=document.getElementById("num1").value;
y=document.getElementById("num2").value;
z=parseInt(x)*parseInt(y);
document.getElementById("result").value=z;
};
//除法运算
function chu(){
var x,y,z;
x=document.getElementById("num1").value;
y=document.getElementById("num2").value;
z=parseInt(x)/parseInt(y);
document.getElementById("result").value=z;
};
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td colspan="2">计算器</td>
</tr>
<tr>
<td>数字一</td>
<td><input type="text" id="num1" name="num1"></td>
</tr>
<tr>
<td>数字二</td>
<td><input type="text" id="num2" name="num2"></td>
</tr>
<tr>
<td>结果</td>
<td><input type="text" id="result" name="result"></td>
</tr>
<tr>
<td colspan="2">
<input type="button" name="jia" id="jia" value="+" onclick="jia()"> <input type="button" name="jian" id="jian" value="-" onclick="jian()">
<input type="button" name="cheng" id="cheng" value="×" onclick="cheng()"> <input type="button" name="chu" id="chu" value="/" onclick="chu()"> </td>
</tr>
</table>
</body>
</html>

Code 2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript实现计算器</title>
<style type="text/css">
input{
width:30px;
height:20px;
text-align:center;
}
#tbCalculator td
{
text-align:center;
vertical-align:middle;
}
</style>
<script type="text/javascript">
var result; //保存点击运算符之前输入框中的数值
var operator; //保存运算符
var isPressEqualsKey = false; //记录是否按下”=“键
//数字键事件
function connectionDigital(control)
{
var txt = document.getElementById(&#39;txtScream&#39;);
if(isPressEqualsKey)
{ 
txt.value = ""; //已进行过计算,则清空数值输入框重新开始
isPressEqualsKey = false;
}
//数值输入已经存在小数点,则不允许再输入小数点
if(txt.value.indexOf(&#39;.&#39;) > -1 && control.value == &#39;.&#39;)
return false;
txt.value += control.value; //将控件值赋给数值输入框中
}
//退格键事件
function backspace()
{
var txt = document.getElementById(&#39;txtScream&#39;);
txt.value = txt.value.substring(0,txt.value.length - 1);
}
//ce键事件:清空数字输入框
function clearAll()
{
document.getElementById(&#39;txtScream&#39;).value = "";
result = "";
operator = "";
}
// +、-、*、/ 事件
function calculation(control)
{
//将运算符保存入全局变量中
operator = control.value; 
var txt = document.getElementById(&#39;txtScream&#39;);
if(txt.value == "")return false; //数值输入框中没有数字,则不能输入运算符
//将数值输入框中的值保存到计算表达式中
result = txt.value; 
//清空输入框,以待输入操作值
txt.value = ""; 
}
//计算结果
function getResult()
{
var opValue;
//计算表达式中存在运算符
var sourseValue = parseFloat(result);
var txt = document.getElementById(&#39;txtScream&#39;);
if(operator == &#39;*&#39;)
opValue = sourseValue * parseFloat(txt.value);
else if(operator == &#39;/&#39;)
opValue = sourseValue / parseFloat(txt.value);
else if(operator == &#39;+&#39;)
opValue = sourseValue + parseFloat(txt.value);
else if(operator == &#39;-&#39;)
opValue = sourseValue - parseFloat(txt.value);
txt.value = opValue;
isPressEqualsKey = true;
result = "";
opValue = "";
}
</script>
</head>
<body>
<table id="tbCalculator" width="200" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#0066FF">
<tr>
<td height="30" colspan="4" align="center">
<input type="text" name="txtScream" id="txtScream" style="width:180px; border-style:none; text-align:right;" readonly="readonly" /> </td>
</tr>
<tr>
<td height="30" colspan="2">
<input type="button" name="btnCE" id="btnCE" value="C E" style="width:80px;" align="right"; onclick="clearAll();" /></td>
<td height="30" colspan="2">
<input type="button" name="btn10" id="btn10" value="Backspace" style="width:80px;" align="right"; onclick="backspace();" /></td>
</tr>
<tr>
<td height="30"><input type="button" name="btn7" id="btn7" value="7" onclick="connectionDigital(this);" /></td>
<td><input type="button" name="btn8" id="btn8" value="8" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn9" id="btn9" value="9" onclick="connectionDigital(this);" /></td>
<td><input type="button" name="btn6" id="btn6" value="/" onclick="calculation(this);" /></td>
</tr>
<tr>
<td height="30">
<input type="button" name="btn4" id="btn4" value="4" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn5" id="btn5" value="5" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn6" id="btn6" value="6" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn13" id="btn13" value="*" onclick="calculation(this);" /></td>
</tr>
<tr>
<td height="30">
<input type="button" name="btn1" id="btn1" value="1" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn2" id="btn2" value="2" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn3" id="btn3" value="3" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btn18" id="btn18" value="-" onclick="calculation(this);" /></td>
</tr>
<tr>
<td height="30"><input type="button" name="btn0" id="btn0" value="0" onclick="connectionDigital(this);"/></td>
<td><input type="button" name="btndot" id="btndot" value="." onclick="connectionDigital(this);" /></td>
<td><input name="btn22" type="button" id="btn22" value="=" onclick="getResult();" /></td>
<td><input type="button" name="btn23" id="btn23" value="+" onclick="calculation(this);" /></td>
</tr>
</table>
</body>
</html>

Method 3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta http-equiv="description" content="javascript计算器,由脚本之家制作" /> 
<title>计算器</title> 
<script type="text/javascript"> 
alert("本计算器由脚本之家制作"); 
function getResult(type){ 
if(checkData()){ 
} 
var no1=parseInt(document.jisuanqi.no1.value); 
var no2=parseInt(document.jisuanqi.no2.value); 
var result; 
switch(type){ 
case &#39;+&#39;: 
result = no1+no2; 
break; 
case &#39;-&#39;: 
result =no1-no2; 
break; 
case &#39;*&#39;: 
result =no1*no2; 
break; 
case &#39;/&#39;: 
result =no1/no2; 
break; 
case &#39;%&#39;: 
result =no1%no2; 
break; 
} 
document.jisuanqi.result.value=result; 
} 
function checkData(){ 
if(document.jisuanqi.no1.value==""){ 
alert("第一个数字不能为空!请重新输入"); 
return; 
} 
if(document.jisuanqi.no2.value==""){ 
alert("第二个不能为空!请重新输入"); 
return; 
} 
if(document.jisuanqi.no1.value=="0"){ 
alert("第一个不能为零!请重新输入"); 
return; 
} 
if(isNaN(document.jisuanqi.no1.value)){ 
alert("第一个不是数字!请重新输入"); 
return; 
} 
if(isNaN(document.jisuanqi.no2.value)){ 
alert("第二个不是数字!请重新输入"); 
} 
} 
</script> 
</head> 
<body> 
<font size="6" color="#000000">本计算器由脚本之家制作<br>QQ:873695957</font> 
<p align="center" /> 
<form name="jisuanqi"> 
  no1:<input name="no1" /><br> 
  no2:<input name="no2" /><br> 
  result:<input name="result" /><br> 
<input type="button" value="+" onclick="getResult(&#39;+&#39;)" /> 
  <input type="button" value="-" onclick="getResult(&#39;-&#39;)" /> 
  <input type="button" value="*" onclick="getResult(&#39;*&#39;)" /> 
  <input type="button" value="/" onclick="getResult(&#39;/&#39;)" /> 
  <input type="button" value="%" onclick="getResult(&#39;%&#39;)" /> 
  </form> 
</p> 
</body> 
</html>

The above three methods are used to implement pure javascript code to implement the calculator function. I hope you like it.

For more pure javascript code to implement the calculator function (three methods) related articles, please pay attention to the PHP Chinese website!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),