Quonn Bernard
Quonn Bernard

Reputation: 31

Javascript calculator keeps concatenating calculation results with first number entered for next calculation

<body>
<FORM NAME="Calculator">
<TABLE BORDER=4>
<TR>
<TD>
<input type="text"   name="Input" Size="22" value="">


<br>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="button" NAME="one"   VALUE="1" class ="digit" >
<INPUT TYPE="button" NAME="two"   VALUE="2" class ="digit" >
<INPUT TYPE="button" NAME="three" VALUE="3" class ="digit" >
<INPUT TYPE="button" NAME="plus"  VALUE="+" class ="operand">
<br>
<INPUT TYPE="button" NAME="four"  VALUE="4" class ="digit">
<INPUT TYPE="button" NAME="five"  VALUE="5" class ="digit">
<INPUT TYPE="button" NAME="six"   VALUE="6" class ="digit">
<INPUT TYPE="button" NAME="minus" VALUE="-" class="operand">
<br>
<INPUT TYPE="button" NAME="seven" VALUE="7" class ="digit">
<INPUT TYPE="button" NAME="eight" VALUE="8" class ="digit">
<INPUT TYPE="button" NAME="nine"  VALUE="9" class ="digit">
<INPUT TYPE="button" NAME="times" VALUE="*" class ="operand">
<br>
<INPUT TYPE="button" NAME="clear" VALUE="c" class ="special">
<INPUT TYPE="button" NAME="zero"  VALUE="0" class ="digit">
<INPUT TYPE="button" NAME="Execute"  VALUE="=" class ="solve">
<INPUT TYPE="button" NAME="div"   VALUE="/" class ="operand">
<br>
</TD>
</TR>
</TABLE>
</FORM>

<script type = "text/javascript" src="C:\Users\Quonn\Desktop\QBJS\calculatorjs.js">
</script>
</body>

I am building a configurable calculator but I am having some with my logic/getting it to behave exactly how i want. I have two questions.

Question # 1: How can I change my logic so that I can replace "evil eval"?

var timer;
document.onclick = function(x) {
var info = x.target;
clearTimeout(timer);
 timer= setTimeout(function(){addDigit(x);},200);
}

Question #2: How can change my logic in this function so that after a calculation result is displayed, the first number entered for the next calculation isn't just concatenated to the previous calculation's result?

function addDigit(x){
if (x.target.className === "digit" || x.target.className ==="operand") {
    document.Calculator.Input.value += "" + x.target.value;
}

else if (x.target.className === "solve") {
    result = eval(document.Calculator.Input.value);
    document.Calculator.Input.value = result;
}
else  {
   document.Calculator.Input.value = "";
}

}

Upvotes: 3

Views: 1412

Answers (1)

Brian Clozel
Brian Clozel

Reputation: 59201

You are concatenating strings. You should have a look at parseInt / parseFloat; watch out for the radix, otherwise JavaScript will try to guess it...

Upvotes: 1

Related Questions