Tuesday, November 24, 2015

Calculator in JavaScript

A simple calculator that I wrote before using JavaScript as my programming language. The code is very simple and easy to understand.

If you  have some questions please send me an email at jake.r.pomperada@gmail.com and jakerpomperada@yahoo.com

My mobile number here in the Philippines is 09173084360.


Sample Program Output


Program Listing

<html>
<head>
<title>Calculator</title>
<script language = "Javascript">
var a = "";
var b = "";

function compute(x)
{
  if (a == "")
  {
    b = document.calc.num.value + x;
    document.calc.num.value = b;
  }
  else
  {
    a = document.calc.num.value + x;
    document.calc.num.value = a;
  }
}
function equals()
{
  a = eval(document.calc.num.value);
  document.calc.num.value = a;
}
</script>
</head>
<body bgcolor = "#336699" text = "white">
<center>
<form name = "calc">
<br><br>
<input type = "text" name ="num"> </input><br><br>
<input type = "button" name = "btnadd" value = " + " onclick = compute("+")> </input> &nbsp;&nbsp;
<input type = "button" name = "btnsub" value = " - " onclick = compute("-")> </input> &nbsp;&nbsp;
<input type = "button" name = "btnmul" value = " * " onclick = compute("*")> </input> &nbsp;&nbsp;
<input type = "button" name = "btndiv" value = " / " onclick = compute("/")> </input> <br><br>
<input type = "button" name = "btn0" value = " 0 " onclick = compute("0")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn1" value = " 1 " onclick = compute("1")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn2" value = " 2 " onclick = compute("2")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn3" value = " 3 " onclick = compute("3")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn4" value = " 4 " onclick = compute("4")> </input> <br><br>
<input type = "button" name = "btn5" value = " 5 " onclick = compute("5")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn6" value = " 6 " onclick = compute("6")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn7" value = " 7 " onclick = compute("7")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn8" value = " 8 " onclick = compute("8")> </input> &nbsp;&nbsp;
<input type = "button" name = "btn9" value = " 9 " onclick = compute("9")> </input> 

<br><br>
<input type = "button" name = "btnperiod" value = " . " onclick = compute(".")> </input> &nbsp;&nbsp;
<input type = "reset" value = " Clear "> </input> &nbsp;&nbsp;
<input type = "button" name = "btnequal" value = " = " onclick = equals()> </input> 
</form>
</center>
</body>
</html>

No comments:

Post a Comment