-
simple operator question
I wanna allow user to enter 2 values then i add them up togther
<script type="text/javascript">
var x = prompt("Please enter a value for x","")
var y = prompt("Please enter a value for y"," ")
if (x != null && x != "" && y != null && y != "")
{
var result
eval ("result = x" + "y")
document.write("Your result is " + result)
}
</script>
eg: i key 1 for x and 2 for y the result i get is 12 instead of 3
pls help
-
first of all, you need to add ; to those lines
second of all, i dont know the answer...
erm...
result=eval(x+y);
?
ok, well now (in Mozilla 1.5) its actually displaying something...but you're right, it is "12"... ummm..
take a look here
-
you need to use the parseInt function so that the strings are treated as numbers and not just concatanated together
Code:
<script type="text/javascript">
var x = prompt("Please enter a value for x","")
var y = prompt("Please enter a value for y"," ")
if (x != null && x != "" && y != null && y != "")
{
var result = eval (parseInt(x) + parseInt(y))
document.write("Your result is " + result)
}
</script>
-
-
The eval is not necessary, just
parseInt(x) + parseInt(y)
suffices.