Home > Article > Web Front-end > JavaScript implements a simple calculator
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='text' id='txt1' /> <select id='select'> <option value='+'>+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> <option value="%">%</option> </select> <input type='text' id='txt2' /> <input type='button' value=' = ' onclick="count()"/> <!--通过 = 按钮来调用创建的函数,得到结果--> <input type='text' id='answer' /> </body> </html>
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!