# Write a simple calculator in JavaScript

• 2020-03-30 04:23:27
• OfStack

This method is super simple, the idea is very worthy of recommendation, friends reference it

``````
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript  Simple calculator </title>
<script>
//Define the global variable & PI;               Var one = "1"; < br / >
var two="2";
var three="3";
var four="4";
var five="5";
var six="6";
var seven="7";
var eight="8";
var nine="9";
var zero="0";
var plus="+",minus="-",multiply="*",divide="/",decimal=".";
function enter(obj,string){
obj.expr.value+=string;
}
function compute(obj){// Click on the equal "=" The function called by the button ;                  obj.expr.value=eval(obj.expr.value);// with JS Have to eval() Method to calculate name for expr In the formula               }
</script>
<body>
<form name="calc" id="calc" action="">
<table border="1">
<td colspan="4"><input type="text" name="expr" size="30" action="compute(this.form)" /></td>
<tr>
<td><input type="button" value=" 7 " onclick="enter(this.form,seven)" /></td>
<td><input type="button" value=" 8 " onclick="enter(this.form,eight)" /></td>
<td><input type="button" value=" 9 " onclick="enter(this.form,nine)" /></td>
<td><input type="button" value=" / " onclick="enter(this.form,divide)" /></td>
</tr>
<tr>
<td><input type="button" value=" 4 " onclick="enter(this.form,four)" /></td>
<td><input type="button" value=" 5 " onclick="enter(this.form,five)" /></td>
<td><input type="button" value=" 6 " onclick="enter(this.form,six)" /></td>
<td><input type="button" value=" * " onclick="enter(this.form,multiply)" /></td>
</tr>
<tr>
<td><input type="button" value=" 1 " onclick="enter(this.form,one)" /></td>
<td><input type="button" value=" 2 " onclick="enter(this.form,two)" /></td>
<td><input type="button" value=" 3 " onclick="enter(this.form,three)" /></td>
<td><input type="button" value=" - " onclick="enter(this.form,minus)" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value=" 0 " onclick="enter(this.form,zero)" /></td>
<td><input type="button" value=" . " onclick="enter(this.form,decimal)" /></td>
<td><input type="button" value=" + " onclick="enter(this.form,plus)" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value=" = " onclick="compute(this.form)" /></td>
<td colspan="2"><input type="button" value="AC" onclick="form.reset()"/></td>
</tr>
</table>
</form>
</body>
</html>
``````

Is not super NB code, great god level!

Related articles: