Table of Contents
JS implements a simple calculator
Home Web Front-end JS Tutorial Teach you a trick to implement a simple calculator

Teach you a trick to implement a simple calculator

Apr 22, 2021 am 09:16 AM
javascript calculator

This article will give you a detailed introduction to the method of implementing a simple calculator in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Teach you a trick to implement a simple calculator

JS implements a simple calculator

Page layout design (HTML CSS)

 due to the previous blog There is a detailed explanation of html and css. Again, I will not go into details and go directly to the code. Because the JQuery selector is used in js, JQuery is introduced in the html using the <script></script> tag. In the html, the calculator event cal() is bound to each button click and the current click object is passed in. this.
  .html file:

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>简单计算器</title>
    <link rel="stylesheet" type="text/css" href="./style.css"> <!-- css样式 -->
   
    <script src="https://code.jquery.com/jquery-latest.min.js"></script> <!-- 引用JQuery库 --></head><body>
    <p>
        <table>
            <tr>
                <td colspan="3"><input type="text" value="0"/></td>
            </tr>
            <tr>
                <td><button id="c11" onclick="cal(this)">+</button></td>
                <td><button id="c12" onclick="cal(this)">-</button></td>
                <td><button id="c13" onclick="cal(this)">×</button></td>
                <td><button id="c14" onclick="cal(this)">/</button></td>
            </tr>
            <tr>
                <td><button id="c21" onclick="cal(this)" value="7">7</button></td>
                <td><button id="c22" onclick="cal(this)" value="8">8</button></td>
                <td><button id="c23" onclick="cal(this)" value="9">9</button></td>
                <td rowspan="2"><button id="c24" onclick="cal(this)">C</button></td>
            </tr>
            <tr>
                <td><button id="c31" onclick="cal(this)" value="4">4</button></td>
                <td><button id="c32" onclick="cal(this)" value="5">5</button></td>
                <td><button id="c33" onclick="cal(this)" value="6">6</button></td>
            </tr>
            <tr>
                <td><button id="c41" onclick="cal(this)" value="1">1</button></td>
                <td><button id="c42" onclick="cal(this)" value="2">2</button></td>
                <td><button id="c43" onclick="cal(this)" value="3">3</button></td>
                <td rowspan="2"><button id="c44" onclick="cal(this)">=</button></td>
            </tr>
            <tr>
                <td colspan="2"><button id="c51" onclick="cal(this)" value="0">0</button></td>
                <td><button id="c53" onclick="cal(this)">.</button></td>
            </tr>
        </table>
    </p>
    <script src = "./calculator.js"></script> <!-- js脚本 --></body></html>
Copy after login

  .css file:

input{
    width: 200px;
    height:50px;
    margin-bottom: 10px;
    padding: 0;
    font:18px bold;}button{
    width: 50px;
    height: 40px;
    margin-bottom: 10px;
    border: 1px dashed black;
    background-color: #ffc4cc;}#c24{
    height: 93px;}#c44{
    height: 93px;}#c51{
    width: 122px;}#c44,#c24,#c14{
    margin-left:10px;}
Copy after login

  Static page as shown:
Teach you a trick to implement a simple calculator

Implement the calculation part ( JS)

1. Function: realize simple addition, subtraction, multiplication and division calculations of numerical values, and clear screen function
2. Operation: For example: 123×29; click 1, 2, 3 ,, click the × sign, click 2, 9 in sequence, and finally click =, you can calculate the result 3567
. The example is shown in the figure: Teach you a trick to implement a simple calculator
Teach you a trick to implement a simple calculator
3. Disadvantages:

  • Negative number calculations cannot be performed, and NaN errors will occur;
  • Cannot perform continuous calculations, and can only perform operations between two numbers at a time; if you want to continue calculations on the previous results, you can directly press Operation symbol and the next number; to start a new calculation, you need to clear the screen first.

4. Idea display:

  • Text box display: Because the content displayed in the text box changes in real time according to the clicked button, in order to make modifications simple, Here we use the JQuery selector to select the text box and assign it to a global variable input. Then we just modify its value according to the val() method of input.

The code is as follows:

var input = $("input");
Copy after login
  • Button id acquisition: Because later we have to perform different operations based on different buttons, so in cal() The first step in the function is to obtain the id of the button, which will be used for subsequent judgment.

The code is as follows:

let btn = e.id;
Copy after login
  • Numerical input: Determine whether it is a number or decimal point based on the id of the button. If so, perform a numeric input operation . First determine whether the value of the current text box is 0. If it is 0, overwrite the input value with the current input; if it is not 0, connect the current input behind the input value.

The code is as follows:

//若input的值为0
input.val(btn_value);//若input的值非0
input.val(input.val()+btn_value);
Copy after login
  • Symbol input: Determine whether it is an arithmetic symbol based on the id of the button. If so, perform the symbol input operation. If continuous operations are not considered, first determine whether the value of the current text box contains, The symbolic link follows the input value.

The code is as follows:

//若input的值含有+、×、/
 alert("连续运算功能未上线!")//若input的值不含有+、×、/
input.val(input.val()+当前运算符号);
Copy after login
  • Numerical calculation: Determine whether it is an equal sign based on the id of the button. If so, perform numerical calculation operations. To make a selection judgment, use the indexOf() method to determine which punctuation mark, ×, / is contained in the input value, and then use the position of the symbol as a separation, use the substring() method to intercept the value in front of the symbol, force it to be converted into a Float type, and then assign it to num1, intercept the value behind the symbol and force it to be converted into Float type and then assign it to num2 to perform corresponding calculations. (Note that the denominator cannot be 0 during division)

The code is as follows:

if(input_value.indexOf("+")!==-1){
        pos = input_value.indexOf("+");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1+num2);
    }
    else  if(input_value.indexOf("-")!==-1){
        pos = input_value.indexOf("-");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1-num2);
    }
    else  if(input_value.indexOf("×")!==-1){
        pos = input_value.indexOf("×");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1*num2);
    }
    else  if(input_value.indexOf("/")!==-1){
        pos = input_value.indexOf("/");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        if(num2-0 === 0){
            alert("分母不能为0!");
        }
        else{
            input.val(num1/num2);
        }
    }
Copy after login
  • Clear screen: Determine whether it is the symbol C according to the id of the button. If so, clear the screen.

The code is as follows:

input.val(0);
Copy after login

5. The JavaScript file is as follows:

"use strict"var input = $("input");function cal(e){
    let btn = e.id;
    //清零
    if( btn === "c24"){
        input.val(0);
    }
    //数值输入
    else if(btn === "c51"||btn === "c41"||btn === "c42"||btn === "c43"
        ||btn === "c31"||btn === "c32"||btn === "c33"
        ||btn === "c21"||btn === "c22"||btn === "c23"){
        let btn_value = document.getElementById(btn).getAttribute("value");
        if( input.val() === "0" ){
            input.val(btn_value);
        }
        else{
            input.val(input.val()+btn_value);
        }
    }
    else if(btn === "c11"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"+");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c12"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"-");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c13"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"×");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c14"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"/");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c53"){
        input.val(input.val()+".");
    }
    else if(btn === "c44"){
        let pos,num1,num2;
        let input_value = input.val();
        if(input_value.indexOf("+")!==-1){
            pos = input_value.indexOf("+");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1+num2);
        }
        else  if(input_value.indexOf("-")!==-1){
            pos = input_value.indexOf("-");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1-num2);
        }
        else  if(input_value.indexOf("×")!==-1){
            pos = input_value.indexOf("×");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1*num2);
        }
        else  if(input_value.indexOf("/")!==-1){
            pos = input_value.indexOf("/");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            if(num2-0 === 0){
                alert("分母不能为0!");
            }
            else{
                input.val(num1/num2);
            }

        }
    }}
Copy after login

[Recommended learning: javascript advanced tutorial

The above is the detailed content of Teach you a trick to implement a simple calculator. For more information, please follow other related articles on 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

An efficient Fibonacci sequence calculator written in PHP An efficient Fibonacci sequence calculator written in PHP Mar 21, 2024 am 10:06 AM

Efficient Fibonacci sequence calculator: PHP implementation of Fibonacci sequence is a very classic mathematical problem. The rule is that each number is equal to the sum of the previous two numbers, that is, F(n)=F(n -1)+F(n-2), where F(0)=0 and F(1)=1. When calculating the Fibonacci sequence, it can be implemented recursively, but performance problems will occur as the value increases. Therefore, this article will introduce how to write an efficient Fibonacci using PHP

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles