I am new in JavaScript & I am creating a simple calculator.
But I have some problems with the eval()
function.
My script:
function calc(fld){
var firstNo = 0 ;
var secNo = 0 ;
var num = fld.name.charAt(2);
var op = fld.name.charAt(0);
if(op == "t"){op = "-";}
else if(op == "z"){op = "*";}
else if(op == "e"){op = "=";}
else if(op == "j"){op = "+";}
else if(op == "d"){op = "/";}
else { op ="";}
if (op != "=") {eval("document.calc1.res").value += num + op ;}
else {
// This line doesn't work correctly
document.calc1.res.value = eval("document.calc1.res.value") ;
// nor this one
// document.calc1.res.value = eval("document.calc1.res").value ;
}
And this is the HTML:
<form id="calc" name="calc1" method="post">
<input type="text" name="res" id="res"><br />
<input type="button" value="7" id="no7" name="no7" onclick="calc(this)"></input type="button" value=""><input type="button" value="8" id="no8" name="no8" onclick="calc(this)"></input type="button" value=""><input type="button" value="9" id="no9" name="no9" onclick="calc(this)"></input type="button" value=""><br />
<input type="button" value="4" id="no4" name="no4" onclick="calc(this)"></input type="button" value=""><input type="button" value="5" id="no5" name="no5" onclick="calc(this)"></input type="button" value=""><input type="button" value="6" id="no6" name="no6" onclick="calc(this)"></input type="button" value=""><br />
<input type="button" value="1" id="no1" name="no1" onclick="calc(this)"></input type="button" value=""><input type="button" value="2" id="no2" name="no2" onclick="calc(this)"></input type="button" value=""><input type="button" value="3" id="no3" name="no3" onclick="calc(this)"></input type="button" value=""><br />
<input type="button" value="-" id="no1" name="t" onclick="calc(this)">
<input type="button" value="*" id="no1" name="z" onclick="calc(this)">
<input type="button" value="=" id="no1" name="e" onclick="calc(this)">
<!--This line works correctly-->
<INPUT TYPE="button" NAME="DoIt" VALUE=" = " OnClick="document.calc1.res.value = eval(document.calc1.res.value)">
<input type="button" value="/" id="no1" name="d" onclick="calc(this)">
<input type="button" value="+" id="no1" name="j" onclick="calc(this)">
</form>
In HTML code there is two equal signs. My problem is there.
When I wanted to evaluate expression in the JS file it did not work, but it was working in HTML file. I mentioned lines with comments.
What are differences between these lines?