Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement a simple Calculator with Javascript Code

Shulou Source: shulou.com Published: 2022-05-31 11:48:12 09月30日 Update

This article introduces the knowledge of "how to use Javascript code to achieve a simple calculator". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1.html code

/ / enter the first number +-* / / drop-down menu, let the user select the operator they need / / enter the second number = / / when you click equals, the result will be output / / the result will be stored here

2.JS code

Var btn_result=document.getElementById ('btn'); / / get the ID var num1=document.getElementById of the equal sign (' txt-num1'); / / get the ID var num2=document.getElementById of the first number ('txt-num2'); / / get the ID var result=document.getElementById of the second number (' txt-result'); / / get the result ID var drop=document.getElementById ('dropdown') / / get the drop-down menu ID btn_result.onclick=function () {/ / this code means that the operation of the two numbers is all caused by the equal sign, and when you click the equal sign, it will make the two values operate var v1=parseFloat (num1.value); / / convert the num to numeric string- > number var v2=parseFloat (num2.value); var v3 values drop.valuesovereignty / use v3 to store the value of the drop-down menu var num / num is used to receive the result of the operation of two numbers switch (v3) {/ / determine which operator the user chooses, and perform the operation case "+": num=v1+v2; break; case "-": num=v1-v2; break; case "*": num=v1*v2; break; case "/": num=v1/v2; break; default: num=v1+v2; break;} result.value=num / / Save the results to result} "how to use Javascript code to implement a simple calculator" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Operation code result number equal sign menu drop-down calculator two content numeric more user knowledge operator storage input output practical learned Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL macOS Apple Shulou Technology NVidia