Home Web Front-end JS Tutorial Pure javascript code to implement calculator function (three methods)

Pure javascript code to implement calculator function (three methods)

Feb 04, 2017 pm 02:15 PM

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

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

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

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 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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles